无法添加或更新子行:外键约束失败

时间:2017-02-09 23:28:23

标签: c# mysql foreign-keys primary-key

生病直截了当。我有两张桌子:

  1. 客户信息
  2. 订单
  3. 现在,由于客户可以拥有0或更多订单,因此我使用Index在这两个表之间创建了关系。在父表中,公司名称是主键,公司名称是索引。

    1. 我知道数据类型,大小和引擎应该是相同的。
    2. 我也知道公司名称应该存在于父表中,以便我们可以修改子表。
    3. 我已经加倍检查所有这些但我仍然在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();
      

      这是将数据插入子表的代码

      Relation Designer view

      我应该使用SET FOREIGN_KEY_CHECKS = 0;如果我做的有什么缺点 提前谢谢你

1 个答案:

答案 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();
相关问题