这个问题在这里已有答案:
我有一个访问数据库与我的工作,我试图插入但我不断得到。
'您无法添加或更改记录,因为“项目”表中需要相关记录。
我正在运行此查询:INSERT INTO Tasks (Assigned,Project,Description) VALUES (@assign,@project,@description)
在这个结构:picture of database structure in access
在C#中使用此代码,使用OleDb ...命令和连接,这些命令和连接适用于其他查询:
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是文本字符串。谢谢你的帮助。
史蒂夫正确地确定了你必须以正确的顺序放置参数的错误。我的修复是按顺序排列我的参数。