Home > Database > Mysql Tutorial > JDBC获取Mysql自动增长字段代码_MySQL

JDBC获取Mysql自动增长字段代码_MySQL

WBOY
Release: 2016-06-01 13:44:52
Original
922 people have browsed it

bitsCN.com

Mysql aotu_increment这个功能在主从关系中经常用到。MySQL没有oracle的专门序列,加上以前的项目使用的是select max(*)来实现这个功能,也是没有深究。后来对比发出max(*)的方法要多一次select数据库,效率肯定不如用java来实现。

方法1、mysql有select LAST_INSERT_ID()可以获取最后的auto_increment。所在可用select last_insert_id()来代替max(*),这样在数据表中就可设定auto_increment字段了。这个方法在多线程并发操作下,比较起max(*)有较大的优势。

方法2、使用java有提供getGeneratedKeys来实现获取最后increment ID。
片断代码如下:

pstmt.executeUpdate();
conn.commit();
//获取auto_increment
int aotuId;
rs = pstmt.getGeneratedKeys();
while(rs.next()){
autoId = rs.getInt(1);
}

作者“实践记录”

bitsCN.com
Related labels:
yes
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template