JAVA自己管理MySQL自增id_java插入mysql一条数据,如何返回自增的ID?

在实际操作中,我们常常有一些各种古怪的需求,比如现在这个。数据库的table中有一个自增的id字段,插入数据库后,要求返回刚刚插入那条数据的id。

在单线程情况下,这当然是一个很简单的问题。首先获得数据库的最大id,给将要插入的语句id赋值为MAX+1,然后插入即可。

Oracle也很容易实现,给这个table建立一个sequence,每次都向这个sequence获取下一个id,效率也是价格公道童叟无欺。

但是,给多线程下的mysql返回刚刚插入的id,这似乎有点小为难。一个立刻可以想到的方法是,给插入操作加个锁,插入后查询MAX id,然后解开锁。但是这个显然是不怎么讲究了。

网上翻了下,有很多种方法解决这个问题,不过最后选择了getGeneratedKeys这个方法。

getGeneratedKeys是Statement下的一个方法,说明如下:

Retrieves any auto-generated keys created as a result of executing this Statement object. If this Statement object did not generate any keys, an empty ResultSet object is returned.

Note:If the columns which represent the auto-generated keys were not specified,the JDBC driver implementation will determine the columns which best represent the auto-generated keys.

Return: a ResultSet object containing the auto-generated key(s) generated by the execution of this Statement object

Exception:SQLException if a database access error occurs or this method is called on a closed Statement

SQLFeatureNotSupportedException if the JDBC driver does not support this method since 1.4

简而言之,这东西可以返回它自动生成的值。因为每次使用插入的时候,我们都是从Connection中生成instance的,所以没有线程安全的问题也就不需要加锁。

听起来有点抽象不如来两行代码演示下:

假定要插入一个有auto_increment的的id和类型varchar(255)的name的table,只输入name,输出id或者错误提示。

public int insert(String name) {

Connection conn = null;

PreparedStatement ps = null;

ResultSet rs = null;

int retNum = -1;

try {

conn = iDBPool.tryGetConnection();// get Connection

if (conn == null) return -1;

String sql = "insert into example_table(name) values(?)";

ps = conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS); //

ps.setString(1,name);

ps.executeUpdate();

rs = ps.getGeneratedKeys();

if(rs.next()){

retNum = rs.getInt(1);

}else {

retNum = -1;

}

} catch (Exception e) {

Log.getLog().info(e.getMessage());

e.printStackTrace();

} finally {

iDBPool.release(conn);

try {

if (null != ps) ps.close();

if (null != rs) rs.close();

} catch (SQLException e) {

e.printStackTrace();

}

}

return retNum;

}

如上,完毕。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值