无法使用JDBC从MySQL数据库获取新生成的主键 [英] Not able to get the newly generated primary key from MySQL database using JDBC

查看:207
本文介绍了无法使用JDBC从MySQL数据库获取新生成的主键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Statement.RETURN_GENERATED_KEYS标志在数据库中的每次插入之后获取新生成的主键值.

I am using Statement.RETURN_GENERATED_KEYS flag to obtan the newly generated primary key value after every insert in the database.

这是代码段:

Connection conn = null;
conn = getDBConnection(); //Susseccfully returns a proper Connection object
PreparedStatement stmt = null;
String sql = "INSERT INTO ..."; //Proper error free INSERT query
stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);//to obtain the new primary key
i = stmt.executeUpdate();//the value of i is always 1 :(

无法理解为什么会这样.我的司机是com.mysql.jdbc.Driver

Not able to understand why this is happening. My driver is com.mysql.jdbc.Driver

编辑:主键的数据类型在数据库中为BIGINT,在表的第二列中.

The primary key's data tyoe is BIGINT in the DB and its the second column in the table.

推荐答案

executeUpdate()返回受影响的行数.

调用stmt.getGeneratedKeys()以获得具有生成的密钥的ResultSet:

Call stmt.getGeneratedKeys() to get a ResultSet with the generated keys:

long key = -1L;
PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);//to obtain the new primary key
// execute statement
int affectedRows = stmt.executeUpdate();
ResultSet rs = stmt.getGeneratedKeys();
// get generated key
if (rs != null && rs.next()) {
  key = rs.getLong(1);
}

这篇关于无法使用JDBC从MySQL数据库获取新生成的主键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆