我想使用PreparedStatement在表中插入一行。表有3列(int、String、String)。问题是int列是AUTO_INCREMENT,所以我想把这个变量留空,让数据库来做这项工作(它是一个id)。不过,我还没有发现如何做到这一点!
这是一个MySQL数据库。
发布于 2012-08-04 08:30:16
这相对简单,只需从列列表中省略自动增量列即可:
insert into mytbl(str1, str2) values (?, ?)
准备语句,设置两个参数,并在非查询模式下执行。
发布于 2012-08-04 08:29:54
只需在sql查询字符串中提供字符串条目,数据库就会填充auto_increment字段:
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();
发布于 2012-08-04 08:35:48
如果该字段已经是自动增量,则只需填充其他两个字段即可。下面是一个示例
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
复制相似问题