• mysql 获取自增id的值的方法


    原生jdbc方式:

    Statement.getGeneratedKeys()

    示例:

    Statement stmt = null;
    ResultSet rs = null;
    
    try {
    
        //
        // Create a Statement instance that we can use for
        // 'normal' result sets assuming you have a
        // Connection 'conn' to a MySQL database already
        // available
    
        stmt = conn.createStatement();
    
        //
        // Issue the DDL queries for the table for this example
        //
    
        stmt.executeUpdate("DROP TABLE IF EXISTS autoIncTutorial");
        stmt.executeUpdate(
                "CREATE TABLE autoIncTutorial ("
                + "priKey INT NOT NULL AUTO_INCREMENT, "
                + "dataField VARCHAR(64), PRIMARY KEY (priKey))");
    
        //
        // Insert one row that will generate an AUTO INCREMENT
        // key in the 'priKey' field
        //
    
        stmt.executeUpdate(
                "INSERT INTO autoIncTutorial (dataField) "
                + "values ('Can I Get the Auto Increment Field?')",
                Statement.RETURN_GENERATED_KEYS);
    
        //
        // Example of using Statement.getGeneratedKeys()
        // to retrieve the value of an auto-increment
        // value
        //
    
        int autoIncKeyFromApi = -1;
    
        rs = stmt.getGeneratedKeys();
    
        if (rs.next()) {
            autoIncKeyFromApi = rs.getInt(1);
        } else {
    
            // throw an exception from here
        }
    
        System.out.println("Key returned from getGeneratedKeys():"
            + autoIncKeyFromApi);
    } finally {
    
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException ex) {
                // ignore
            }
        }
    
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException ex) {
                // ignore
            }
        }
    }

    也有使用SELECT LAST_INSERT_ID() 注意:并发可能会出现问题。示例:

    Statement stmt = null;
    ResultSet rs = null;
    
    try {
    
        //
        // Create a Statement instance that we can use for
        // 'normal' result sets.
    
        stmt = conn.createStatement();
    
        //
        // Issue the DDL queries for the table for this example
        //
    
        stmt.executeUpdate("DROP TABLE IF EXISTS autoIncTutorial");
        stmt.executeUpdate(
                "CREATE TABLE autoIncTutorial ("
                + "priKey INT NOT NULL AUTO_INCREMENT, "
                + "dataField VARCHAR(64), PRIMARY KEY (priKey))");
    
        //
        // Insert one row that will generate an AUTO INCREMENT
        // key in the 'priKey' field
        //
    
        stmt.executeUpdate(
                "INSERT INTO autoIncTutorial (dataField) "
                + "values ('Can I Get the Auto Increment Field?')");
    
        //
        // Use the MySQL LAST_INSERT_ID()
        // function to do the same thing as getGeneratedKeys()
        //
    
        int autoIncKeyFromFunc = -1;
        rs = stmt.executeQuery("SELECT LAST_INSERT_ID()");
    
        if (rs.next()) {
            autoIncKeyFromFunc = rs.getInt(1);
        } else {
            // throw an exception from here
        }
    
        System.out.println("Key returned from " +
                           "'SELECT LAST_INSERT_ID()': " +
                           autoIncKeyFromFunc);
    
    } finally {
    
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException ex) {
                // ignore
            }
        }
    
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException ex) {
                // ignore
            }
        }
    }

    mybatis封装后的配置如下:

    <insert id="insert" parameterType="Post" useGeneratedKeys="true" keyProperty="id">

    调用

    postDao.add(post);

    和以前一样结果后返回1,使用post.getId()可以获取到自增的id。

    参考文献:

    【1】http://dev.mysql.com/doc/connector-j/en/connector-j-usagenotes-last-insert-id.html

    【2】http://stackoverflow.com/questions/12241260/get-auto-genearated-key-for-the-inserted-record-in-mybatis

  • 相关阅读:
    kubeadm部署K8S集群v1.16.3
    MySQL5.7Gtid主从复制总是遇到日志被清等出现无法正常主从复制
    ORACLE数据库SQL优化 not in 与not exits
    某控股公司OA系统ORACLE DG搭建
    阿里云ECS服务器上搭建keepalived+mha+mysql5.6+gtid+一主两从+脚本判断架构踩的坑
    生产案例:开发不小心把某个表数据清了,没有逻辑备份,有物理备份
    生产案例:突然产生大量的归档日志,导致磁盘空间满了无法登陆数据库
    maxscale读写分离
    MYSQL EXPLAIN执行计划命令详解(支持更新中)
    vue 解决 post请求下载文件,下载的文件损坏打不开,结果乱码
  • 原文地址:https://www.cnblogs.com/davidwang456/p/4836327.html
Copyright © 2020-2023  润新知