JAVA 向数据库中插入数据并获取主键的方法(逐渐补充)

通过JDBC向数据库中插入数据后,有时需要获取主键,总结方法如下,以备查阅,

简单jdbc操作获取主键

    public int addUser(User user) {
        Connection conn = null;
        PreparedStatement ps = null;
        int i = 0;
        try {
            String sql = "insert into user "
                    + "(ID,LOGIN_NAME,PASSWORD,EMAIL,RECOMMENDER) "
                    + "values (user_id_seq.nextval,?,?,?,? )";
            conn = JdbcDBPoolUtil.getConnection();
            String [] ids = {"id"};
            ps = conn.prepareStatement(sql,ids);
            ps.setString(1, user.getLoginName());
            ps.setString(2, user.getPassword());
            ps.setString(3, user.getEmail());
            ps.setString(4, user.getRecommender());
            i = ps.executeUpdate();
            ResultSet rs = ps.getGeneratedKeys();
            if(rs.next()){
                System.out.println("生成的主键是:"+rs.getInt(1));//此处只能使用getInt(1) 的方式获取,也可将主键值返回
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally{
            JdbcDBPoolUtil.close(conn, ps, null);
        }
        return i;
    }

SpringBoot插入数据是获取主键

@Insert("insert into user (id,name,password) values (#{id},#{name},#{password})")
@SelectKey(before = true, statement = "select user_seq.nextval from dual",resultType = Integer.class, keyProperty = "id")
public int save(User user);
//在插入之前先获取主键值,并将主键值赋值给user对象的id属性,再执行插入操作时user对
//象中就有id属性,插入操作执行完毕后,可从user对象中获取id 即是主键值。

你可能感兴趣的:(ORACLE)