JAVA中獲取剛插入數據庫中的數據ID(主鍵,自動增長)


//添加用戶
    public User add(User user) {
        Connection con = null;
        PreparedStatement stm = null;
        ResultSet rs = null;
        User info = null;
        try{
            // 與數據庫建立連接
            con = JDBCUtils.getConnection();
            //sql語句
            String sql = "insert into user_info(username,password) value(?,?)";
            stm=con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
            //填充占位符
            stm.setString(1,user.getName());
            stm.setString(2,user.getPassword());

            stm.executeUpdate();
            //獲取最后ID。
            rs=stm.getGeneratedKeys();
             //int n = stm.executeUpdate(); // 返回受影響的行數
            if(rs.next()){
                // 這里還要再實例化一次,找了幾個鍾啊,回憶總想哭
                info = new User();
                int id = rs.getInt(1);
                info.setId(id);
                return info;
            }else{
                return null;
            }
        }
        catch (Exception exc){
            exc.printStackTrace();
        }
        finally {
            // 關閉資源
            JDBCUtils.close(null,stm,con);
        }

        return null;
    }

關鍵語句stm=con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); rs=stm.getGeneratedKeys();
設置增長起始值alter table 表名 AUTO_INCREMENT=1000; 這里設置起始值是1000


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM