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

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

问题描述

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

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

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

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.

我将 Java 与 JDBC 和 PostgreSQL 结合使用.

I am using Java with a JDBC and PostgreSQL.

推荐答案

使用 PostgreSQL,您可以通过 RETURNING 关键字来实现:

With PostgreSQL you can do it via the RETURNING keyword:

PostgresSQL - 返回

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

它将返回anyfield"的值.anyfield"可能是一个序列,也可能不是.

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

要将其与 JDBC 一起使用,请执行以下操作:

To use it with JDBC, do:

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

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

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