有时候会需要获取刚刚插入的记录的主键:
使用PrepareStatament的一种重构可以实现返回主键。
PrepareStatament 有多种重构,各自有不同的作用。
package cn.itcast.jdbc;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class OtherApi {
public static void main(String[] args) throws SQLException {
int id=create();
System.out.println(id);
}
//获取最近一次插入的数据的主键
static int create() throws SQLException {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = JdbcUtils.getConnection();
String sql = "insert into user(name,birthday,money)values('name1','1987-1-1',400)";
//prepareStatement的多种重构
ps = conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
ps.executeUpdate();
//使用getGeneratedKeys取得主键的结果集;
rs=ps.getGeneratedKeys();
int id=0;
if(rs.next())
id=rs.getInt(1);
return id;
} finally {
JdbcUtils.free(rs, ps, conn);
}
}
}