通常我们在应用中对mysql执行了insert操作后,需要获取插入记录的自增主键,这时候通常用getGeneratedKeys()方法获取主键
1. 获得数据库返回的主键
insert into book values(null,'编程珠玑',45);
2. 获得主键的步骤
conn.prepareStatement(sql,autoGeneratedKeys)
autoGeneratedKeys是一个int值 ,1代表返回生成的主键,2代表不返回生成的主键;为了方便记忆,使用 Statement.Statement.RETURN_GENERATED_KEYS,Statement.NO_GENERATED_KEYS
3.获得生成的主键
ResultSet rs=ps.getGeneratedKesy();
rs.next();
int userno= rs.getInt(1);
Statement stmt = null; ResultSet rs = null; try { stmt = conn.createStatement(java.sql.ResultSet.TYPE_FORWARD_ONLY, java.sql.ResultSet.CONCUR_UPDATABLE); // ... // 省略若干行(如上例般创建demo表) // ... stmt.executeUpdate( "INSERT INTO autoIncTutorial (dataField) " + "values ('Can I Get the Auto Increment Field?')", Statement.RETURN_GENERATED_KEYS); // 向驱动指明需要自动获取generatedKeys! int autoIncKeyFromApi = -1; rs = stmt.getGeneratedKeys(); // 获取自增主键! if (rs.next()) { autoIncKeyFromApi = rs.getInt(1); } else { // throw an exception from here } rs.close(); rs = null; System.out.println("Key returned from getGeneratedKeys():" + autoIncKeyFromApi); } finally { ... }