22

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.

3 Answers 3

20

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();
Sign up to request clarification or add additional context in comments.

Comments

19

That's relatively simple, just leave out the autoincrement column from the column list:

insert into mytbl(str1, str2) values (?, ?)

Prepare the statement, set the two parameters, and execute in non query mode.

4 Comments

Thanks, everyone pretty much said the same but your were first so u'll get the right :)
In MySQL, pass NULL to the ID column also make it AUTO_INCREMENT insert into t (id, col1, col2) values (NULL, ?, ?) or insert into t (id, col1, col2) values (?, ?, ?) with java code stmt.setNull(1, java.sql.Types.INTEGER)
can we use this ? insert into mytbl(str1, str2) values ('Example', ?) and then ps.setString(1,"String2") or we have to use ps.setString(2,"String2")
@DeepSidhu1313 Since there's only one parameter, you call setString(1,...), not 2.
5

If the field is already autoincrement, it is enough to populate just the other two fields. Here an example

String sql = "INSERT INTO mytableName("
    + "fistStringColumnName,"
    + "secondStringColumnName) "
    +  "VALUES(?,?)";

try (PreparedStatement pstmt = connection.prepareStatement(sql)) {

    // Set the values
    pstmt.setString(1, "firstString");
    pstmt.setString(2, "secondString");

    // Insert 
    pstmt.executeUpdate();

} catch (SQLException e) {

} catch (FileNotFoundException e) {

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.