- public Object insertGetId(String sql, Object... params) throws Exception {
- Connection conn = null;
- PreparedStatement preparedStatement = null;
- ResultSet rs = null;
- try {
- conn= getConnection();
- preparedStatement = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
- setParams(preparedStatement, params);
- preparedStatement.executeUpdate();
- rs = preparedStatement.getGeneratedKeys();
- Object retId = null;
- if (rs.next())
- retId = rs.getObject(1);
- else
- throw new Exception("insert or generate keys failed..");
- return retId;
- } catch (Exception e) {
- throw e;
- } finally {
- close(rs);
- close(preparedStatement);
- close(conn);
- }
- }
只需要new对象 并调用方法即可
- try {
- String newId = bd.insertGetId(newInsertSql, null).toString();
- System.out.print("--------------"+newId);
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
参考的文章:
有时候,在用insert插入数据后,想获得刚插入记录的ID,可以利用JDBC的getGeneratedKeys获得INSERT插入后生成的主键ID。本例数据库为mysql,主键ID为int类型,用auto_increment生成。
以下为主要的java代码:
- ps = conn.prepareStatement("insert into test(name) value(?)",Statement.RETURN_GENERATED_KEYS);
- ps.setString(1, "test");
- ps.execute();
- rs = ps.getGeneratedKeys();
- int id=0;//保存生成的ID
- if (rs != null&&rs.next()) {
- id=rs.getInt(1)
- }
本例用到的主要方法为以下两个,可以查阅JDK参考文档:
1、PreparedStatement prepareStatement( String sql, int autoGeneratedKeys) throws SQLException(在java.sql.Connection接口中)
2、ResultSet getGeneratedKeys() throws SQLException(在java.sql.PreparedStatement 接口中)