龙空技术网

mysql 获取自增id的值的方法

架构师笔记 279

前言:

此刻兄弟们对“mysql插入获取id”大概比较珍视,各位老铁们都需要学习一些“mysql插入获取id”的相关知识。那么小编在网上网罗了一些关于“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】

【2】

标签: #mysql插入获取id #mysql获取插入数据的id #mysqlinsertid自增 #mysqlinsert获取id #mysql设置自增id