在JAVA中查询刚插入的记录ID 利用JDBC的getGeneratedKeys获得INSERT插入后生成的主键ID

23 篇文章 1 订阅
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代码

  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 接口中)


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值