JDBC连接获取新增后的主键id

通常我们在mysql中新增insert一条数据之后,都需要获取添加后的主键Id(因为主键id是唯一标识这一行数据的),但是呢,又不能连续执行两个语句。虽然参考了很多博主的文章,使用了事务处理和allowMutiInsert=true属性但似乎都没什么效果。

于是老师给了一个解决方案:

使用getGeneratedKeys()方法获取主键。

1. 获得数据库返回的主键      

String sql = "insert into t_user values(null,'"+usersVO.getNickName()+"','"+usersVO.getPassword()+"','"+usersVO.getPhone()+"','"+usersVO.getEmail()+"')";


  2. 获得主键的步骤
            conn.prepareStatement(sql,autoGeneratedKeys)
            autoGeneratedKeys是一个int值 ,1代表返回生成的主键,2代表不返回生成的主键;

             为了方便记忆,使用                 Statement.Statement.RETURN_GENERATED_KEYS,Statement.NO_GENERATED_KEYS
3.获得生成的主键
  ResultSet rs=ps.getGeneratedKesy();
  rs.next();
  int userno= rs.getInt(1);

代码如下:

public int getKeyId(Connection conn,String sql){
        try {
            statement= conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE);
            statement.executeUpdate(sql,Statement.RETURN_GENERATED_KEYS);
            rs= statement.getGeneratedKeys();
           if(rs.next()){
               int num =rs.getInt(1);
               return num;
           }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            //关闭数据库
            this.closConn(conn);
        }
        return 0;
    }

猜你喜欢

转载自blog.csdn.net/weixin_52875840/article/details/123443985