javaweb中建立mysql,添加记录外键报错,原因是什么?

pstmt.setString(1,r.getRid());
pstmt.setString(2,r.getPid());
pstmt.setString(3,r.getCname());
pstmt.setString(4,r.getRname());
pstmt.setString(5,r.getDescription());
其中数据库中,pid和cname是外键,我这么写就报错Cannot add or update a child row: a foreign key constraint fails (`teammanagement`.`requirement`, CONSTRAINT `require_ibfk_1` FOREIGN KEY (`pid`) REFERENCES `project` (`Projectid`))

但是如果我改成pstmt.setString(1,r.getRid());
pstmt.setString(2,"1");//pid对应的别的表中有“1”
pstmt.setString(3,"微软");//cname对应的别的表中有"微软"
pstmt.setString(4,r.getRname());
pstmt.setString(5,r.getDescription());
就成功了,为什么?

你的category 中c.getId()是主键,如果c.getId()!=-1 ,你有重复插入id了,导致在数据库中用重复的id,你else方法里边应该是update,不应该是insert,在if里边你就是用insert 但是id不能为null ,因为那是主键追问

复制粘贴没什么意思的
rid是主键,我并没有犯这种低级错误

温馨提示:答案为网友推荐,仅供参考
相似回答