【发布时间】:2014-05-28 15:21:58
【问题描述】:
我正在为 Access 数据库使用 OleDB 提供程序,使用 C# VS2010 进行开发
我有一个Products表和Suppliers表
当我调试这段代码时:
//open connection
con.Open();
//set command query for inserting a product
com2 = new OleDbCommand(@"INSERT INTO Products (ProductName,Model,Provider,Manufacturer,ReleasedDate,Quantity,SupplierID)
VALUES (@name,@model,@provider,@manf,@date,@quantity,@supp)", con);
/* ADDING PARAMETERS TO THE COMMMAND */
com2.Parameters.AddWithValue("@name", textBox1.Text);
com2.Parameters.AddWithValue("@model", textBox2.Text);
com2.Parameters.AddWithValue("@provider", textBox4.Text);
com2.Parameters.AddWithValue("@manf", textBox5.Text);
com2.Parameters.AddWithValue("@date", DbType.DateTime).Value = dateTimePicker1.Value;
com2.Parameters.AddWithValue("@quantity", Convert.ToInt32(textBox6.Text));
// com2.Parameters.AddWithValue("@price", Convert.ToInt32(textBox3.Text));
/* Getting the ID of the Supplier by his/her/it name and adding the value as a parameter */
com = new OleDbCommand("Select SupplierID from Suppliers WHERE SupplierName=@name",con);
com.Parameters.AddWithValue("@name",comboBox1.SelectedValue);
int str = (int)com.ExecuteScalar();
com2.Parameters.AddWithValue("@supp", str);
//INSERT EXECUTION
com2.ExecuteNonQuery();
MessageBox.Show("Product Added To Stock");
con.Close();
程序运行良好并执行查询,但是当我取消注释该行
com2.Parameters.AddWithValue("@price", Convert.ToInt32(textBox3.Text));
并将com2查询字符串编辑为:
com2 = new OleDbCommand(@"INSERT INTO Products (ProductName,Model,Provider,Manufacturer,ReleasedDate,Quantity,SupplierID,Price)
VALUES (@name,@model,@provider,@manf,@date,@quantity,@supp,@price)", con);
程序在com2.ExecuteNonQuery(); 行崩溃并出现以下错误:
You cannot add or change a record because a related record is required in table 'Suppliers'.
注意事项:
- 如果您想知道我为什么要添加价格,那是因为我没有 从一开始就添加它
- Price 列存在于表
Products中 - 我删除了两个表中的所有记录
- 价格列类型:数字 - 长整型
- SupplierID 是 Suppliers 表中的主键
- 调试时,
str的值为 4,与其中一个供应商的值相同
【问题讨论】:
-
列类型是什么?
-
@EhsanSajjad 数字 - 长整数
-
我怀疑供应商 ID 错误,供应商表中不存在该 ID 的行
-
是的。确保
SupplierID存在于Supplier表中,因为是外键,所以出现了。 -
@EhsanSajjad 我调试了程序,
str的值为 4 ,这是其中一个供应商的 ID
标签: c# database ms-access-2010