java.sql.SQLException:尝试从 java 插入数据库时出现重复项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24168217/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
java.sql.SQLException: Duplicate entry for key when trying to insert in database from java
提问by AminePaleo
this is my table in mysql
这是我在 mysql 中的表
CREATE TABLE `mydb`.`mytab` (
`email` VARCHAR(45) NOT NULL,
`name` VARCHAR(45) NULL,
PRIMARY KEY (`email`));
and my code in java is
我在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();
and this is what i get when i run the file in netbeans
这就是我在 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)
so how do i get it to work?
那么我该如何让它工作呢?
thanks for replying
感谢回复
采纳答案by Rakesh KR
In your table you have already have an entry with "email".
在您的表格中,您已经有一个带有“电子邮件”的条目。
Here in the table column email is set as PrimaryKey. So duplication cannot be possible.
此处在表列中将电子邮件设置为 PrimaryKey。所以复制是不可能的。
Note :
笔记 :
Your Table is mytab
under database mydb
. But you are inserting into spacespacer.mytab
.
您的表mytab
在 database 下mydb
。但是您正在插入spacespacer.mytab
.
回答by Vivin
This is because you already have "email" in your table which you have set as primary key. So you cannot add more emails called "email". Try querying your table to check if you already have that record. As a suggestion, don't use email as a primary key. It will result in slow indexing and searching since its a varchar and can be long.
这是因为您的表中已经有“电子邮件”,您已将其设置为主键。因此,您无法添加更多名为“电子邮件”的电子邮件。尝试查询您的表以检查您是否已经拥有该记录。建议不要使用电子邮件作为主键。它会导致索引和搜索缓慢,因为它是一个 varchar 并且可能很长。
回答by Paul
Do not use 'email' as key, even when it is unique. Rule of thumb, use int
or long
as primary key.
不要使用“电子邮件”作为键,即使它是唯一的。经验法则,使用int
或long
作为主键。