gpt4 book ai didi

java.sql.SQLException : Duplicate entry for key when trying to insert in database from java 异常

转载 作者:行者123 更新时间:2023-11-29 06:36:43 25 4
gpt4 key购买 nike

这是我在mysql中的表

CREATE TABLE `mydb`.`mytab` (

`email` VARCHAR(45) NOT NULL,
`name` VARCHAR(45) NULL,

PRIMARY KEY (`email`));

我的java代码是

Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/spacespacer", "root", "");
PreparedStatement state=con.prepareStatement("INSERT INTO `spacespacer`.`mytab` VALUES (?, ?);");
state.setString(1, "email");
state.setString(2, "name");
state.executeUpdate();

这是我在 netbeans 中运行文件时得到的结果

run:
Exception in thread "main" java.sql.SQLException: Duplicate entry 'email' for key 'PRIMARY'
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2847)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1531)
at com.mysql.jdbc.ServerPreparedStatement.serverExecute(ServerPreparedStatement.java:1347)
at com.mysql.jdbc.ServerPreparedStatement.executeInternal(ServerPreparedStatement.java:958)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1957)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1880)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1741)
at spacespacer.SpaceSpacer.main(SpaceSpacer.java:30)
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)

那么我该如何让它工作呢?

感谢回复

最佳答案

在您的表中,您已经有一个带有“电子邮件”的条目。

这里的表列 email 被设置为 PrimaryKey。所以不可能重复。

注意:

您的表是数据库 mydb 下的 mytab。但是您正在插入 spacespacer.mytab

关于java.sql.SQLException : Duplicate entry for key when trying to insert in database from java 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24168217/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com