Insert row into database with PreparedStatement

Lucas Arrefelt picture Lucas Arrefelt · Aug 4, 2012 · Viewed 70.1k times · Source

I want to insert a row into a table using PreparedStatement. The table got 3 columns(int, String, String). The thing is that the int column is AUTO_INCREMENT, so I want to leave that variable empty and let the database do that job (It's an id). Haven't found out how to do this though!

It's an MySQL database.

Answer

Reimeus picture Reimeus · Aug 4, 2012

Just provide the String entries in your sql query string and the database will populate the auto_increment field:

String insertSQL = "INSERT INTO MyTable (StrCol1, StrCol2) VALUES (?, ?)";
PreparedStatement preparedStatement = dbConnection.prepareStatement(insertSQL);
preparedStatement.setString(1, "Val 1");
preparedStatement.setString(2, "Val 2");
preparedStatement.executeUpdate();