2016-01-29 91 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(?,?,?,?,?,?)」我仍然不完全理解程序的作品,但它以某種方式認識到,這些價值正在插入正確的順序。這個問題最終與數據在程序中其他地方無法正確解析有關 –

相關問題