Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JDBC Insert with autoincrement

Tags:

java

sql

mysql

jdbc

I'm executing a query using MySQL library in java. In my db structure there's a column called cod_nfs (primary key, not null and auto_increment). Usually in every insert query I set the value to null and after query execution it increment last id but doing this in java give me exception.

That's the code:

String SQL = "INSERT INTO infosetdata(cod_nfs,savingDate_nfs,attributeValue_nfs,codInfoSet_nfs,codColumn_nfs,codRow_nfs) VALUES (null,'2019-01-08',?,?,?,?)";


for( String value : values ) {
                ps = conn.prepareStatement(SQL);
                ps.setString(1, value);
                ps.setInt(2, dataId);
                ps.setInt(3, y);
                ps.setInt(4, x);
                ps.executeUpdate();
                y++;
            }

How can I execute the query with auto increment id?

like image 765
FranCode Avatar asked Aug 28 '26 00:08

FranCode


2 Answers

Do not include the primary key column in the insert.

Also, do not prepare the statement every time. Just do it once.

String SQL = "INSERT INTO infosetdata (savingDate_nfs,attributeValue_nfs,codInfoSet_nfs,codColumn_nfs,codRow_nfs) " 
           + "VALUES ('2019-01-08',?,?,?,?)";
ps = conn.prepareStatement(SQL);
for( String value : values ) {
   ps.setString(1, value);
   ps.setInt(2, dataId);
   ps.setInt(3, y);
   ps.setInt(4, x);
   ps.executeUpdate();
   ResultSet rs = ps.getGeneratedKeys();
   if (rs.next()) {
     int pk = rs.getInt(1);
     System.out.println("Generated PK = " + pk);
   }
   y++;
}

As you see, you can recover the generated PK value using PreparedStatement.getGeneratedKeys().

like image 195
The Impaler Avatar answered Aug 29 '26 14:08

The Impaler


You shouldn't set a value for cod_nfs because it is already set as auto incremental. Try below:

String SQL = "INSERT INTO infosetdata(savingDate_nfs,attributeValue_nfs,codInfoSet_nfs,codColumn_nfs,codRow_nfs) VALUES ('2019-01-08',?,?,?,?)

If it gives error, make sure your cod_nfs column is set as auto incremental. Try running:

ALTER TABLE infosetdata MODIFY cod_nfs INT(11) NOT NULL AUTO_INCREMENT

Thanks @Mark Rotteveel to help on that issue in the comments.

like image 32
Eray Balkanli Avatar answered Aug 29 '26 15:08

Eray Balkanli