Insert row into database with PreparedStatement

前端 未结 3 1723
没有蜡笔的小新
没有蜡笔的小新 2021-01-17 08:32

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 l

相关标签:
3条回答
  • 2021-01-17 08:51

    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) {
    
    }
    
    0 讨论(0)
  • 2021-01-17 08:53

    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.

    0 讨论(0)
  • 2021-01-17 09:05

    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();
    
    0 讨论(0)
提交回复
热议问题