以批处理模式从 MySQL 中检索多行的 auto_increment 值

Retrieve auto_increment value of multiple rows from MySQL in batch mode

有一个 mysql table 主键为 id int auto_increment, 我需要使用多个 insert 语句批量插入多行,并禁用 autocommit,如下所示:

SET autocommit=0;
INSERT INTO dummy(NAME, `size`, create_date) VALUES('test', 1, NOW());
INSERT INTO dummy(NAME, `size`, create_date) VALUES('test', 2, NOW());
COMMIT;

是否可以获取每个生成的 ID,而不仅仅是最后一个 ID。

如果是,每个id是什么时候生成的,如何通过jdbc获取所有id?

谢谢。

如果您想通过 JDBC 检索 AUTO_INCREMENT 密钥,您需要使用 JDBC 功能(RETURN_GENERATED_KEYS.getGeneratedKeys()) ,像这样:

try (Connection conn = DriverManager.getConnection(myConnectionString, "root", "beer")) {
    try (Statement st = conn.createStatement()) {
        st.execute(
                "CREATE TEMPORARY TABLE dummy (" +
                    "`id` INT AUTO_INCREMENT PRIMARY KEY, " +
                    "`NAME` VARCHAR(50), " +
                    "`size` INT, " +
                    "`create_date` DATETIME " +
                ")");
    }
    conn.setAutoCommit(false);
    System.out.println("AutoCommit is OFF.");
    String sql = "INSERT INTO dummy(NAME, `size`, create_date) VALUES('test', ?, NOW())";
    try (PreparedStatement ps = conn.prepareStatement(
            sql, 
            PreparedStatement.RETURN_GENERATED_KEYS)) {
        // first batch
        ps.setInt(1, 1);  // `size` = 1
        ps.addBatch();
        ps.setInt(1, 2);  // `size` = 2
        ps.addBatch();
        ps.executeBatch();
        System.out.println("First batch executed. The following AUTO_INCREMENT values were created:");
        try (ResultSet rs = ps.getGeneratedKeys()) {
            while (rs.next()) {
                System.out.println(rs.getInt(1));
            }
        }
        try (Statement st = conn.createStatement()) {
            sql = "SELECT COUNT(*) AS n FROM dummy";
            try (ResultSet rs = st.executeQuery(sql)) {
                rs.next();
                System.out.println(String.format("The table contains %d row(s).", rs.getInt(1)));
            }
        }
        conn.rollback();
        System.out.print("Transaction rolled back. ");
        try (Statement st = conn.createStatement()) {
            sql = "SELECT COUNT(*) AS n FROM dummy";
            try (ResultSet rs = st.executeQuery(sql)) {
                rs.next();
                System.out.println(String.format("The table contains %d row(s).", rs.getInt(1)));
            }
        }
        // second batch
        ps.setInt(1, 97);  // `size` = 97
        ps.addBatch();
        ps.setInt(1, 98);  // `size` = 98
        ps.addBatch();
        ps.setInt(1, 99);  // `size` = 99
        ps.addBatch();
        ps.executeBatch();
        System.out.println("Second batch executed. The following AUTO_INCREMENT values were created:");
        try (ResultSet rs = ps.getGeneratedKeys()) {
            while (rs.next()) {
                System.out.println(rs.getInt(1));
            }
        }
    }
    try (Statement st = conn.createStatement()) {
        sql = "SELECT COUNT(*) AS n FROM dummy";
        try (ResultSet rs = st.executeQuery(sql)) {
            rs.next();
            System.out.println(String.format("The table contains %d row(s).", rs.getInt(1)));
        }
    }
}

... 产生以下控制台输出:

AutoCommit is OFF.
First batch executed. The following AUTO_INCREMENT values were created:
1
2
The table contains 2 row(s).
Transaction rolled back. The table contains 0 row(s).
Second batch executed. The following AUTO_INCREMENT values were created:
3
4
5
The table contains 3 row(s).