JDBC 3种获得mysql插入数据的自增字段值的方法。

1. Retrieving AUTO_INCREMENT Column Values using Statement.getGeneratedKeys()

2. Retrieving AUTO_INCREMENT Column Values using SELECT LAST_INSERT_ID()

3. Retrieving AUTO_INCREMENT Column Values in Updatable ResultSets

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.Statement;

public class RetrievAutoIncrementTest{

public void init() throws Exception {

Statement stmt = null;

ResultSet rs = null;

Connection conn = null;

try {

Class.forName(“com.mysql.jdbc.Driver”);

conn = DriverManager

.getConnection(“jdbc:mysql://localhost/test?”,”root”, “admin”);

// Issue the DDL queries for the table for this example

stmt = conn.createStatement();

stmt.executeUpdate(“DROP TABLE IF EXISTS autoIncTutorial”);

//创建数据库表autoIncTutorial。stmt.executeUpdate(“CREATE TABLE autoIncTutorial (”

+ “priKey INT NOT NULL AUTO_INCREMENT, ”

+ “dataField VARCHAR(64), PRIMARY KEY (priKey))”);

} finally {

if (rs != null) {

try {

rs.close();

} catch (Exception e) {

}

}

if (stmt != null) {

try {

stmt.close();

} catch (Exception e) {

}

}

if (conn != null) {

try {

conn.close();

} catch (Exception e) {

}

}

}

}

public void test1() throws Exception {

Statement stmt = null;

ResultSet rs = null;

Connection conn = null;

try {

Class.forName(“com.mysql.jdbc.Driver”);

conn = DriverManager

.getConnection(“jdbc:mysql://localhost:3306/test”,”root”, “admin”);

// 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(java.sql.ResultSet.TYPE_FORWARD_ONLY,

java.sql.ResultSet.CONCUR_UPDATABLE);

//Insert one row that will generate an AUTO INCREMENT key in the ‘priKey’ field

for (int i = 0; i < 10; i++) {

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

}

rs.close();

rs = null;

System.out.println(“Key returned from getGeneratedKeys():”

+autoIncKeyFromApi);

}

} finally {

if (rs != null) {

try {

rs.close();

} catch (Exception e) {

}

}

if (stmt != null) {

try {

stmt.close();

} catch (Exception e) {

}

}

if (conn != null) {

try {

conn.close();

} catch (Exception e) {

}

}

}

}

public void test2() throws Exception {

Statement stmt = null;

ResultSet rs = null;

Connection conn = null;

try {

//

// Create a Statement instance that we can use for

// ‘normal’ result sets.

Class.forName(“com.mysql.jdbc.Driver”);

conn = DriverManager

.getConnection(“jdbc:mysql://localhost/test”,”root”, “admin”);

stmt = conn.createStatement();

// Insert one row that will generate an AUTO INCREMENT

// key in the ‘priKey’ field

for (int i = 0; i < 10; i++) {

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

}

rs.close();

System.out.println(“Key returned from ”

+ “‘SELECT LAST_INSERT_ID()’: ” +autoIncKeyFromFunc);

}

} finally {

if (rs != null) {

try {

rs.close();

} catch (Exception e) {

}

}

if (stmt != null) {

try {

stmt.close();

} catch (Exception e) {

}

}

if (conn != null) {

try {

conn.close();

} catch (Exception e) {

}

}

}

}

public void test3() throws Exception {

Statement stmt = null;

ResultSet rs = null;

Connection conn = null;

try {

// Create a Statement instance that we can use for

// ‘normal’ result sets as well as an ‘updatable’

// one, assuming you have a Connection ‘conn’ toa MySQL database already available

Class.forName(“com.mysql.jdbc.Driver”);

conn = DriverManager

.getConnection(“jdbc:mysql://localhost/test”,”root”, “admin”);

stmt = conn.createStatement(java.sql.ResultSet.TYPE_FORWARD_ONLY,

java.sql.ResultSet.CONCUR_UPDATABLE);

for (int i = 0; i < 10; i++) {

// Example of retrieving an AUTO INCREMENT key from an updatable result set

rs = stmt.executeQuery(“SELECT priKey, dataField “+ “FROM autoIncTutorial”);

rs.moveToInsertRow();

rs.updateString(“dataField”, “AUTO INCREMENT here?”);

rs.insertRow();// the driver adds rows at the end

rs.last();

// We should now be on the row we just inserted

int autoIncKeyFromRS = rs.getInt(“priKey”);

rs.close();

rs = null;

System.out.println(“Key returned for inserted row: “+autoIncKeyFromRS);

}

} finally {

if (rs != null) {

try {

rs.close();

} catch (Exception e) {

}

}

if (stmt != null) {

try {

stmt.close();

} catch (Exception e) {

}

}

if (conn != null) {

try {

conn.close();

} catch (Exception e) {

}

}

}

}

public static void main(String[] args) throws Exception {

RetrievAutoIncrementTesttest = new RetrievAutoIncrementTest();

test.init();

test.test1();//测试第一种获取自增字段的值

test.test2();//测试第二种获取自增字段的值

test.test3();//测试第三种获取自增字段的值

}

}

http://www.codesky.net/article/200906/168971.html

jdbc 3种获得mysql插入数据的自增字段值的方法_JDBC 3种获得mysql插入数据的自增字段值的方法...相关推荐

  1. jdbc连接mysql正规方法_JDBC基础篇(MYSQL)——通过JDBC连接数据库的三种方式

    package day01_jdbc; import java.sql.Connection; import java.sql.Driver; import java.sql.DriverManage ...

  2. mysql增删改查 工具类_JDBC工具类实现对数据库数据的增删改查

    1.先将连接的地址和账号密码放在属性文件中,本地连接直接///代替,java1.6以后自动加载驱动 url = jdbc:mysql:///testdata user =root password= ...

  3. 【转载文章】记录一次MySQL两千万数据的大表优化解决过程,提供三种解决方案...

    问题概述 使用阿里云rds for MySQL数据库(就是MySQL5.6版本),有个用户上网记录表6个月的数据量近2000万,保留最近一年的数据量达到4000万,查询速度极慢,日常卡死.严重影响业务 ...

  4. php mysql插入的数据有引号,PHP引号转义中解决POST,GET,Mysql数据自动转义问题

    在处理mysql和GET.POST的数据时,常常要对数据的引号进行转义操作. PHP中有三个设置可以实现自动对'(单引号),"(双引号),\(反斜线)和 NULL 字符转转. PHP称之为魔 ...

  5. MyBatis插入大量数据效率对比:foreach、SqlSession、sql三种方式批量插入

    用mybatis插入数据执行效率对比,对比三种方式(测试数据库为MySQL), 使用 SqlSessionFactory,每一批数据执行一次提交 使用mybatis-plus框架的insert方法,f ...

  6. MySQL不会丢失数据的秘密,就藏在它的 7种日志里

    进入正题前先简单看看MySQL的逻辑架构,相信我用的着. MySQL逻辑架构 MySQL的逻辑架构大致可以分为三层: 第一层:处理客户端连接.授权认证,安全校验等. 第二层:服务器server层,负责 ...

  7. 数据简化社区2018年全球数据库总结及18种主流数据库介绍(公号回复“数据库2018”下载典藏版PDF报告)

    数据简化社区2018年全球数据库总结及18种主流数据库介绍(公号回复"数据库2018"下载典藏版PDF报告) 秦陇纪 数据简化DataSimp 今天 数据简化DataSimp导读: ...

  8. pymysq向mysql写数据 为什么本地无法查看_从运维角度浅谈MySQL数据库优化,中小企业DBA必会...

    原文:http://www.enmotech.com/web/detail/1/712/1.html(复制链接,打开浏览器即可查看原文) 作者:搬砖游击队 一个成熟的数据库架构并不是一开始设计就具备高 ...

  9. solr mysql 分词_solr 7+tomcat 8 + mysql实现solr 7基本使用(安装、集成中文分词器、定时同步数据库数据以及项目集成)...

    基本说明 Solr是一个开源项目,基于Lucene的搜索服务器,一般用于高级的搜索功能: solr还支持各种插件(如中文分词器等),便于做多样化功能的集成: 提供页面操作,查看日志和配置信息,功能全面 ...

最新文章

  1. 关于链表和指针变量的使用说明,可用于框架设计
  2. 9A0-054 Exam 专业认证
  3. .Net Core + 微信赋能企业级智能客服系统--学习笔记
  4. Networdx小案例学习
  5. 中国蔬菜汤市场趋势报告、技术动态创新及市场预测
  6. AngularJS中$timeout和$interval的用法详解
  7. 浅谈Entity Framework中的数据加载方式
  8. timezone java_如何将Java日期转换为特定的TimeZone格式
  9. envi 打开影像报错:‘HISTOGRAM:illegal binsize or max/min‘.The result maybe invalid
  10. java普通工程打war包_普通java工程(Java Project)打jar包
  11. vb.net 教程 1-20 例
  12. WebStorm改变字体大小以及更换背景颜色
  13. 数学知识(一)-有理数
  14. 串口通信校验方式(even,odd,space,mark)UART数据波形分析
  15. python unrar问题_Python-使用unrar库时Couldn't find path to unrar library的解决办法
  16. Java8新特性之空指针异常的克星Optional类
  17. ubuntu16.04 安装opencv的viz模块
  18. MySQL安全登录策略
  19. Herrig Schiefspiegler望远镜
  20. 正则表达式匹配非某字符串的情况

热门文章

  1. C# 使用摄像头拍照 支持Win7 64位
  2. C#操作存储过程,输入参数,返回结果
  3. c语言的递归定义有两个要素,C语言-chap8function.ppt
  4. 怎么设计接口测试用例更好——百度大佬“教你写用例”
  5. 软件测试学习笔记之工具江湖的神兵利器
  6. matlab ds18b20 单片机,基于51单片机ds18b20温度检测————设计报告.doc
  7. 政史系列:《社会契约论》读书笔记
  8. 采用Locust对grpc协议进行压测
  9. jmeter监听器你真的会用了吗?每天早下班1小时的技巧来了~
  10. Docker之获取镜像(一)