生病直截了当。我有两张桌子:
现在,由于客户可以拥有0或更多订单,因此我使用Index在这两个表之间创建了关系。在父表中,公司名称是主键,公司名称是索引。
我已经加倍检查所有这些但我仍然在c#
中收到错误"无法添加或更新子行:外键约束失败"
for (int i = 0; i < dtgCart.Rows.Count; i++)
{
command.CommandText = "INSERT INTO order_info (CompanyName,Order_ID,ProductName,Model,Address,Quantity,Price) VALUES(@CompanyName,@Order_ID,@ProductName,@Model,@Address,@Quantity,@Price)";
command.Parameters.AddWithValue("@CompanyName",dtgCart.Rows[i].Cells["CompanyName"]);
command.Parameters.AddWithValue("@Order_ID", dtgCart.Rows[i].Cells["Order_ID"]);
command.Parameters.AddWithValue("@ProductName", dtgCart.Rows[i].Cells["ProductName"]);
command.Parameters.AddWithValue("@Model", dtgCart.Rows[i].Cells["Model"]);
command.Parameters.AddWithValue("@Address", dtgCart.Rows[i].Cells["Address"]);
command.Parameters.AddWithValue("@Quantity",dtgCart.Rows[i].Cells["Quantity"]);
command.Parameters.AddWithValue("@Price",dtgCart.Rows[i].Cells["Price"]);
command.ExecuteNonQuery();
}
Con.Close();
Con.Dispose();
这是将数据插入子表的代码
我应该使用SET FOREIGN_KEY_CHECKS = 0;如果我做的有什么缺点 提前谢谢你
答案 0 :(得分:0)
此代码立即运行
for (int i = 0; i < dtgCart.Rows.Count-1; i++)
{
command.CommandText = "INSERT INTO order_info (CompanyName,Order_ID,ProductName,Model,Address,Quantity,Price) VALUES(@CompanyName,@Order_ID,@ProductName,@Model,@Address,@Quantity,@Price)";
command.Parameters.AddWithValue("@CompanyName",dtgCart.Rows[i].Cells["CompanyName"].Value);
command.Parameters.AddWithValue("@Order_ID", dtgCart.Rows[i].Cells["Order_ID"].Value);
command.Parameters.AddWithValue("@ProductName", dtgCart.Rows[i].Cells["ProductName"].Value);
command.Parameters.AddWithValue("@Model", dtgCart.Rows[i].Cells["Model"].Value);
command.Parameters.AddWithValue("@Address", dtgCart.Rows[i].Cells["Address"].Value);
command.Parameters.AddWithValue("@Quantity",dtgCart.Rows[i].Cells["Quantity"].Value);
command.Parameters.AddWithValue("@Price",dtgCart.Rows[i].Cells["Price"].value);
command.ExecuteNonQuery();
}
Con.Close();
Con.Dispose();