zoukankan      html  css  js  c++  java
  • MySQL外键约束冲突异常:com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (...)

    异常内容

    Error updating database.  Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (`book`.`t_order`, CONSTRAINT `t_order_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `t_user` (`id`))
    

    外键约束冲突,我的错误出在插入的 id 已经存在了,所以产生了冲突。

    外键联系的两个表之间存在依赖关系,主表的还没有的时候,从表自然也不能存在(这就是约束,主键要消失,你下面有从表——不行;从表要新增,你联系的那个主表还没创建——不行)。就像没你老子就没你,同理你老子还没出生,你就要蹦出来,自然也是不行

    此问题关键是错误消息出现在数据库上,所以排错方向也应该在此。

    又一个场景,删除存在外键约束的表数据时,异常:com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails

    解决办法:

    #存在外键约束的表数据无法被删除,删除前需要先删除外键约束
    SET foreign_key_checks = 0;-- 删除外键约束
    truncate table t_order;
    truncate table t_order_item;
    SET foreign_key_checks = 1;-- 启动外键约束
    
  • 相关阅读:
    闽江学院2015-2016学年下学期《软件测试》课程-第五次博客作业
    在Swift中应用Grand Central Dispatch(下)
    在Swift中应用Grand Central Dispatch(上)转载自的goldenfiredo001的博客
    Asp.net mvc 框架揭秘之Asp.net +Mvc简介
    JavaScript数组
    网页校验
    删除弹出提示框_MVC
    业务体会
    判断数组值是否有重复
    sql
  • 原文地址:https://www.cnblogs.com/csyh/p/13518308.html
Copyright © 2011-2022 走看看