在依赖表上插入Access数据库时出现问题

时间:2018-08-06 18:14:49

标签: c# ms-access insert oledb

我有一个试图插入我的工作的访问数据库,但我一直在获取。

  

“您无法添加或更改记录,因为表'Projects'中需要相关记录。

我正在运行以下查询:INSERT INTO Tasks (Assigned,Project,Description) VALUES (@assign,@project,@description)

在此结构上:picture of database structure in access

使用带有OleDb ...的C#代码,这些命令和连接对于其他查询也可以正常工作

private void addTaskBTN_Click(object sender, EventArgs e)
        {
            //the assign id is already known and is of type integer.
            string query = "SELECT Project_ID FROM Projects WHERE Project_Name = @project";
            OleDbConnection con = new OleDbConnection(con_string);
            OleDbCommand cmd = new OleDbCommand(query, con);
            cmd.Parameters.AddWithValue("@project", projectComboBox.Text);
            con.Open();
            OleDbDataReader reader = cmd.ExecuteReader();
            while (reader.Read())
            {
                project_id = Convert.ToInt16(reader[0]);
                Console.WriteLine(project_id);
            }
                
            con.Close();

            Console.WriteLine("submit: " + project_id + " " + employee_id + " " + descriptionTextBox.Text + " " + monthCalendar1.SelectionStart);
            Console.WriteLine(monthCalendar1.SelectionStart);
            query = "INSERT INTO Tasks (Assigned,Project,Description) VALUES (@assign,@project,@description)";
            con = new OleDbConnection(con_string);
            cmd = new OleDbCommand(query, con);
            cmd.Parameters.Clear();
            cmd.Parameters.AddWithValue("@project", project_id);
            cmd.Parameters.AddWithValue("@assign", employee_id);
            cmd.Parameters.AddWithValue("@description", descriptionTextBox.Text.ToString());
            //cmd.Parameters.AddWithValue("@deadline", monthCalendar1.SelectionStart);
            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();
            this.Close();
        }

我尝试查看此问题的其他示例,但我不明白为什么会收到此错误。 @project具有项目主键的有效ID号,@ assign也具有有效的员工ID,@ description是文本字符串。感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

Steve正确地识别出错误的参数,您必须按正确的顺序放置参数。我的解决办法是按顺序排列参数。