写在前面
- 指定返回增长的字段的值connection.prepareStatement(sqlString, Statement.RETURN_GENERATED_KEYS);
- 获得增长的字段的结果集preparedStatement.getGeneratedKeys();
详细过程
Class.forName("com.mysql.jdbc.Driver");
Connection connection = Driver.getConnection(url, "用户名", "密码");
String sqlString = "insert into 表名 values(值, 值)";
//指定返回自增长的字段的值
PreparedStatement preparedStatement = connection.prepareStatement(sqlString, Statement.RETURN_CENERATED_KEYS);
preparedStatement.executeUpdate();
ResultSet generatedKeys = preparedStatement.getGeneratedKeys();
while(generatedKeys.next()) {
generatedKeys.getInt(1);
}
connection.close();
preparedStatement.close();