PreparedStatement.getGeneratedKeys() //得到执行添加操作后自动生成的主键值
PreparedStatement ps = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
ps.executeUpdate();
ResultSet rs = st.getGeneratedKeys();//得到执行添加操作后自动生成的主键值
rs.getInt(1);
public class OtherApi {
public static void main(String[] args) throws SQLException,
InterruptedException {
int id = create();
System.out.println("id:" + id);
}
static int create() throws SQLException {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
// 2.建立连接
conn = JdbcUtils.getConnection();
// conn = JdbcUtilsSing.getInstance().getConnection();
// 3.创建语句
String sql = "insert into user(name,birthday, money) values ('name2 gk', '1987-01-01', 400) ";
ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); //这样设置可以返加添加的这条记录的主键值
ps.executeUpdate();
rs = ps.getGeneratedKeys();//到到添加后的主键值类型是ResultSet
int id = 0;
if (rs.next()){
id = rs.getInt(1);
}
return id;
} finally {
JdbcUtils.free(rs, ps, conn);
}
}
}