3. 通过SQL select LAST_INSERT_ID()
[java] view plain copy
Statement stmt = null;
ResultSet rs = null;
try {
stmt = conn.createStatement();
// ...
// 省略建表
// ...
stmt.executeUpdate(
"INSERT INTO autoIncTutorial (dataField) "
+ "values ('Can I Get the Auto Increment Field?')");
int autoIncKeyFromFunc = -1;
rs = stmt.executeQuery("SELECT LAST_INSERT_ID()"); // 通过额外查询获取generatedKey
if (rs.next()) {
autoIncKeyFromFunc = rs.getInt(1); //得到自增Id,autoIncKeyFromFunc为得到的ID
} else {
// throw an exception from here
}
rs.close();
System.out.println("Key returned from " +
"'SELECT LAST_INSERT_ID()': " +
autoIncKeyFromFunc);
} finally {...}
[java] view plain copy
Statement stmt = null;
ResultSet rs = null;
try {
stmt = conn.createStatement();
// ...
// 省略建表
// ...
stmt.executeUpdate(
"INSERT INTO autoIncTutorial (dataField) "
+ "values ('Can I Get the Auto Increment Field?')");
int autoIncKeyFromFunc = -1;
rs = stmt.executeQuery("SELECT LAST_INSERT_ID()"); // 通过额外查询获取generatedKey
if (rs.next()) {
autoIncKeyFromFunc = rs.getInt(1); //得到自增Id,autoIncKeyFromFunc为得到的ID
} else {
// throw an exception from here
}
rs.close();
System.out.println("Key returned from " +
"'SELECT LAST_INSERT_ID()': " +
autoIncKeyFromFunc);
} finally {...}