Reputation: 97
this is my table in mysql
CREATE TABLE `mydb`.`mytab` (
`email` VARCHAR(45) NOT NULL,
`name` VARCHAR(45) NULL,
PRIMARY KEY (`email`));
and my code in java is
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
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
Upvotes: 1
Views: 18867
Reputation: 163
Do not use 'email' as key, even when it is unique. Rule of thumb, use int
or long
as primary key.
Upvotes: 0
Reputation: 6527
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.
Note :
Your Table is mytab
under database mydb
. But you are inserting into spacespacer.mytab
.
Upvotes: 2
Reputation: 1367
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.
Upvotes: 0