I want to INSERT
a record in a database (which is Microsoft SQL Server in my case) using JDBC in Java. At the same time, I want to obtain the insert ID. How can I achieve this using JDBC API?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- SQL join to get the cartesian product of 2 columns
- sql execution latency when assign to a variable
- How to maintain order of key-value in DataFrame sa
If it is an auto generated key, then you can use
Statement#getGeneratedKeys()
for this. You need to call it on the sameStatement
as the one being used for theINSERT
. You first need to create the statement usingStatement.RETURN_GENERATED_KEYS
to notify the JDBC driver to return the keys.Here's a basic example:
Note that you're dependent on the JDBC driver as to whether it works. Currently, most of the last versions will work, but if I am correct, Oracle JDBC driver is still somewhat troublesome with this. MySQL and DB2 already supported it for ages. PostgreSQL started to support it not long ago. I can't comment about MSSQL as I've never used it.
For Oracle, you can invoke a
CallableStatement
with aRETURNING
clause or aSELECT CURRVAL(sequencename)
(or whatever DB-specific syntax to do so) directly after theINSERT
in the same transaction to obtain the last generated key. See also this answer.In my case ->
I'm using SQLServer 2008, but I have a development limitation: I cannot use a new driver for it, I have to use "com.microsoft.jdbc.sqlserver.SQLServerDriver" (I cannot use "com.microsoft.sqlserver.jdbc.SQLServerDriver").
That's why the solution
conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)
threw a java.lang.AbstractMethodError for me. In this situation, a possible solution I found is the old one suggested by Microsoft: How To Retrieve @@IDENTITY Value Using JDBCThis solution worked for me!
I hope this helps!
I'm hitting Microsoft SQL Server 2008 R2 from a single-threaded JDBC-based application and pulling back the last ID without using the RETURN_GENERATED_KEYS property or any PreparedStatement. Looks something like this:
This blog post nicely isolates three main SQL Server "last ID" options: http://msjawahar.wordpress.com/2008/01/25/how-to-find-the-last-identity-value-inserted-in-the-sql-server/ - haven't needed the other two yet.
Create Generated Column
Pass this geneated Column to your statement
Use
ResultSet
object to fetch the GeneratedKeys on Statement