• JDBC 获取被插入数据的主键ID值


    除了用存储过程还有以下方法可以获取:

     

     

    static int create() throws SQLException {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            // 2.建立连接
            conn = JdbcUtils.getConnection();
            // conn = JdbcUtilsSing.getInstance().getConnection();
            // 3.创建语句
            String sql = "insert into user(name,birthday, money) values ('name2 gk', '1987-01-01', 400) ";
            ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);//参数2最好写上,虽然Mysql不写也能获取但是不代表别的数据库可以做到
            ps.executeUpdate();

            rs = ps.getGeneratedKeys();
            int id = 0;
            if (rs.next())
                id = rs.getInt(1);
            return id;
        } finally {
            JdbcUtils.free(rs, ps, conn);
        }
    }

     

     

     


    getGeneratedKeys
    ResultSet getGeneratedKeys()
                               throws SQLException
    获取由于执行此 Statement 对象而创建的所有自动生成的键。如果此 Statement 对象没有生成任何键,则返回空的 ResultSet 对象。

    注:如果未指定表示自动生成键的列,则 JDBC 驱动程序实现将确定最能表示自动生成键的列。

    返回:
    包含通过执行此 Statement 对象自动生成的键的 ResultSet 对象
    抛出:
    SQLException - 如果发生数据库访问错误,或者在已关闭的 Statement 上调用此方法
    SQLFeatureNotSupportedException - 如果 JDBC 驱动程序不支持此方法
    从以下版本开始:
    1.4
  • 相关阅读:
    教你如何自定义组件
    android应用开发小技巧
    改变Vim在iTerm2中的光标
    Mac添加bash alias
    tmux常用命令
    javascript Date 总结
    ES6箭头函数
    npm常用命令
    ES6 import export
    gitingore
  • 原文地址:https://www.cnblogs.com/flying607/p/3461980.html
Copyright © 2020-2023  润新知