1. 程式人生 > 資料庫 >外來鍵新增失敗:java.sql.SQLException: Cannot add or update a child row: a foreign key constraint fails

外來鍵新增失敗:java.sql.SQLException: Cannot add or update a child row: a foreign key constraint fails

錯誤程式碼

java.sql.SQLException: Cannot add or update a child row: a foreign key constraint fails (book.t_order_item, CONSTRAINT t_order_item_ibfk_1 FOREIGN KEY (order_id) REFERENCES t_order (order_id)) Query: insert into t_order_item(name,count,price,total_price,order_id)values(?,?,?,?,?) Parameters: [Java程式設計思想, 1, 100, 100, 1234511]

嘗試根據錯誤資訊排錯

  • a foreign key constraint fails:外來鍵約束異常
  • 意思就是,設定的外來鍵和對應表的主鍵的值不匹配,即order_id的值在表t_order中沒有匹配上。

解決辦法

  • 找出不匹配的值,修改成匹配的