在Java中插入SQL后访问自动增量标识字段 [英] Access to auto increment identity field after SQL insert in Java
问题描述
有关如何通过 java.sql.Statement.executeUpdate
调用分配给新创建的记录的自动递增标识字段的任何建议?
我知道如何在SQL中为几个数据库平台做这个,但是想知道 java.sql
中存在哪些数据库独立接口要做这个,以及人们在数据库平台上使用这些经验的任何输入。
下面的代码片段应该做ya':
PreparedStatement stmt = conn.prepareStatement(sql,
Statement.RETURN_GENERATED_KEYS);
// ...
ResultSet res = stmt.getGeneratedKeys();
while(res.next())
System.out.println(Generated key:+ res.getInt(1));
这已知适用于以下数据库
- Derby
- MySQL
- SQL Server
对于不起作用的数据库(HSQLDB,Oracle,PostgreSQL等),您需要使用特定于数据库的技巧。例如,在PostgreSQL上,您可以调用 SELECT NEXTVAL(...)
来查询相关序列。
<请注意,
executeUpdate(...)
的参数是类似的。 Any advice on how to read auto-incrementing identity field assigned to newly created record from call through java.sql.Statement.executeUpdate
?
I know how to do this in SQL for several DB platforms, but would like to know what database independent interfaces exist in java.sql
to do this, and any input on people's experience with this across DB platforms.
The following snibblet of code should do ya':
PreparedStatement stmt = conn.prepareStatement(sql,
Statement.RETURN_GENERATED_KEYS);
// ...
ResultSet res = stmt.getGeneratedKeys();
while (res.next())
System.out.println("Generated key: " + res.getInt(1));
This is known to work on the following databases
- Derby
- MySQL
- SQL Server
For databases where it doesn't work (HSQLDB, Oracle, PostgreSQL, etc), you will need to futz with database-specific tricks. For example, on PostgreSQL you would make a call to SELECT NEXTVAL(...)
for the sequence in question.
Note that the parameters for executeUpdate(...)
are analogous.
这篇关于在Java中插入SQL后访问自动增量标识字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!