在JAVA中查询刚插入的记录ID

  1. public Object insertGetId(String sql, Object... params) throws Exception {  
  2.         Connection conn = null;  
  3.         PreparedStatement preparedStatement = null;  
  4.         ResultSet rs = null;  
  5.         try {  
  6.             conn= getConnection();  
  7.             preparedStatement = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);  
  8.             setParams(preparedStatement, params);  
  9.             preparedStatement.executeUpdate();  
  10.             rs = preparedStatement.getGeneratedKeys();  
  11.               
  12.             Object retId = null;  
  13.             if (rs.next())  
  14.                 retId = rs.getObject(1);  
  15.             else  
  16.                 throw new Exception("insert or generate keys failed..");  
  17.             return retId;  
  18.               
  19.         } catch (Exception e) {  
  20.             throw e;  
  21.         } finally {  
  22.             close(rs);  
  23.             close(preparedStatement);  
  24.             close(conn);  
  25.         }  
  26.   
  27.     }  



只需要new对象 并调用方法即可

[java]  view plain  copy
  1. try {  
  2.                             String newId = bd.insertGetId(newInsertSql, null).toString();  
  3.                             System.out.print("--------------"+newId);  
  4.                         } catch (Exception e) {  
  5.                             // TODO Auto-generated catch block  
  6.                             e.printStackTrace();  
  7.                         }  


参考的文章:

     有时候,在用insert插入数据后,想获得刚插入记录的ID,可以利用JDBC的getGeneratedKeys获得INSERT插入后生成的主键ID。本例数据库为mysql,主键ID为int类型,用auto_increment生成。

 

 

以下为主要的java代码

[java]  view plain copy
  1. ps = conn.prepareStatement("insert into test(name) value(?)",Statement.RETURN_GENERATED_KEYS);  
  2. ps.setString(1"test");  
  3. ps.execute();  
  4. rs = ps.getGeneratedKeys();  
  5. int id=0;//保存生成的ID  
  6. if (rs != null&&rs.next()) {  
  7.     id=rs.getInt(1)  
  8. }  

本例用到的主要方法为以下两个,可以查阅JDK参考文档:

1、PreparedStatement prepareStatement( String sql, int autoGeneratedKeys) throws SQLException(在java.sql.Connection接口中)

2、ResultSet getGeneratedKeys() throws SQLException(在java.sql.PreparedStatement 接口中)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值