如何从最后一个插入行获取值? [英] How to get a value from the last inserted row?

查看:129
本文介绍了如何从最后一个插入行获取值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法从最后一个插入的行获取值?



我插入一行,PK会自动增加,我想得到这个PK。只有PK被保证在表中是唯一的。



我使用Java和JDBC和PostgreSQL。



PostgresSQL - RETURNING

  INSERT INTO mytable(field_1,field_2,...)
VALUES(value_1,value_2)RETURNING anyfield


b $ b

它将返回anyfield的值。



要使用JDBC,请执行以下操作:

  ResultSet rs = statement.executeQuery(INSERT ... RETURNING ID); 
rs.next();
rs.getInt(1);


Is there some way to get a value from the last inserted row?

I am inserting a row where the PK will automatically increase, and I would like to get this PK. Only the PK is guaranteed to be unique in the table.

I am using Java with a JDBC and PostgreSQL.

解决方案

With PostgreSQL you can do it via the RETURNING keyword:

PostgresSQL - RETURNING

INSERT INTO mytable( field_1, field_2,... )
VALUES ( value_1, value_2 ) RETURNING anyfield

It will return the value of "anyfield". "anyfield" may be a sequence or not.

To use it with JDBC, do:

ResultSet rs = statement.executeQuery("INSERT ... RETURNING ID");
rs.next();
rs.getInt(1);

这篇关于如何从最后一个插入行获取值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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