Insert row into database with PreparedStatement

前端 未结 3 1746
没有蜡笔的小新
没有蜡笔的小新 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条回答
  •  萌比男神i
    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) {
    
    }
    

提交回复
热议问题