2016-01-29 93 views
2

我注意到这个问题已经被问了很多,但我找不到解释似乎解决了我的具体情况。我有一个连接到本地数据库的C#.NET程序。该程序应该采取一个平面文件,并将数据行添加到数据库中的一个表中,如果它尚未存在的话。C#.NET - 无法添加或更新子行:外键约束失败

这里是我使用的行添加到数据库

//Add a row to the database passed in as db 
public bool AddRow(OdbcConnection db) 
{ 
String sql = "INSERT INTO item " 
      + "(item_id, invent_id, itemsize, color, curr_price, qoh) " 
      + "VALUES(?, ?, ?, ?, ?, ?)"; 
OdbcCommand Command = new OdbcCommand(sql, db); 
Command.Parameters.Add("@ID", OdbcType.Int).Value = this.Item_ID; 
Command.Parameters.Add("@INVID", OdbcType.Int).Value = this.Invent_id; 
Command.Parameters.Add("@SZ", OdbcType.VarChar).Value = this.Itemsize; 
Command.Parameters.Add("@COL", OdbcType.VarChar).Value = this.Color; 
Command.Parameters.Add("@PR", OdbcType.Double).Value = (double)this.Curr_price; 
Command.Parameters.Add("@QOH", OdbcType.Int).Value = this.Qoh; 

int result = Command.ExecuteNonQuery(); //Returns 1 if successful 
if (result > 0) 
    return true; //Was successful in adding 
else 
    return false; //failed to add 
} //end of AddRow 

一旦方法达到Command.ExecuteNonQuery()它引发以下错误的方法:

其他信息:ERROR [HY000 ] [MySQL] [ODBC 5.3(a)Driver] [mysqld-5.7.10-log]无法添加或更新子行:外键约束失败(labdbitem,CONSTRAINT item_ibfk_1 FOREIGN KEY(invent_id)REFERENCES inventoryinvent_id ))

我知道这里的想法是我们正在添加一行到Item表中。我知道该表与Invent_ID属性是外键的Inventory表有关系。这个值似乎是导致错误的原因,尽管它应该符合所有约束条件。

任何人都可以向我暗示我可能忽略的是什么?我应该说这个类是我与C#的第一次交互,并且大部分程序都是该类提供的模板。

回答

1

由于传递了错误的参数顺序,您正在收到该错误。而不是''在你的INSERT语句中,你需要通过参数名称来定义它们:

{ 
     String sql = "INSERT INTO item " 
        + "(item_id, invent_id, itemsize, color, curr_price, qoh) " 
        + "VALUES(@ID, @INVID, @SZ,@COL, @PR, @QOH)"; 
     OdbcCommand Command = new OdbcCommand(sql, db); 
     Command.Parameters.Add("@ID", OdbcType.Int).Value = this.Item_ID; 
     Command.Parameters.Add("@INVID", OdbcType.Int).Value = this.Invent_id; 
     Command.Parameters.Add("@SZ", OdbcType.VarChar).Value = this.Itemsize; 
     Command.Parameters.Add("@COL", OdbcType.VarChar).Value = this.Color; 
     Command.Parameters.Add("@PR", OdbcType.Double).Value = (double)this.Curr_price; 
     Command.Parameters.Add("@QOH", OdbcType.Int).Value = this.Qoh; 

     int result = Command.ExecuteNonQuery(); //Returns 1 if successful 
     if (result > 0) 
      return true; //Was successful in adding 
     else 
      return false; //failed to add 
    } //end of AddRow 
+0

谢谢你指出这个!我会马上检查这个 –

+1

谢谢你检查回来。这实际上并不是我需要的答案,而我的最终程序使用原始格式 - “VALUES(?,?,?,?,?,?)”我仍然不完全理解程序的作品,但它以某种方式认识到,这些价值正在插入正确的顺序。这个问题最终与数据在程序中其他地方无法正确解析有关 –

相关问题