Insert row into database with PreparedStatement

…衆ロ難τιáo~ 提交于 2019-12-19 12:24:50

问题


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.


回答1:


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.




回答2:


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();



回答3:


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) {

}


来源:https://stackoverflow.com/questions/11804906/insert-row-into-database-with-preparedstatement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!