获得自动增长的MySQL主键

时间:2022-01-27 19:22:43

下面的脚本教您如何获得自动增长的MySQL主键,如果您对MySQL主键方面感兴趣的话,不妨一看,相信对您学习MySQL主键方面会有所启迪。

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement; public class GetKey {
ResultSet rs = null;
Connection conn = null;
Statement stmt = null; // 加入同一个连接发生其他查询,Key会被重写所以不准确
public void getId() {
try {
Statement stmt = conn.createStatement();
stmt.executeUpdate("insert into tb (name) values ('Key')");
rs = stmt.executeQuery("SELECT LAST_INSERT_ID()");
int autoIncKeyFromFunc = -1;
if (rs.next()) {
autoIncKeyFromFunc = rs.getInt(1);
System.out.println("autoIncKeyFromFunc: " + autoIncKeyFromFunc);
}
} catch (Exception e) {
System.out.print("有异常发生!");
}
}
// getGeneratedKeys()是每次创建一个Statement 实例,所以是安全的!
public void getId_() {
try {
stmt = conn.createStatement(java.sql.ResultSet.TYPE_FORWARD_ONLY, java.sql.ResultSet.CONCUR_UPDATABLE);
stmt.executeUpdate("insert into tb (name) values ('x')");
int autoIncKeyFromApi = -1;
rs = stmt.getGeneratedKeys();
if (rs.next()) {
autoIncKeyFromApi = rs.getInt(1);
System.out.println("Key returned from getGeneratedKeys():" + autoIncKeyFromApi);
}
} catch (Exception e) {
System.out.print("有异常发生!");
}
}
public static void main(String[] args) {
GetKey get = new GetKey();
get.getId();
get.getId_();
}
}