title | description | author | ms.author | ms.date | ms.service | ms.subservice | ms.topic |
---|---|---|---|---|---|---|---|
Using auto-generated keys |
Learn how the JDBC Driver for SQL Server supports retrieving automatically generated row identifiers when an application performs database operations. |
David-Engel |
davidengel |
08/12/2019 |
sql |
connectivity |
conceptual |
[!INCLUDEDriver_JDBC_Download]
The [!INCLUDEjdbcNoVersion] supports the optional JDBC 3.0 APIs to retrieve automatically generated row identifiers. The main value of this feature is to provide a way to make IDENTITY values available to an application that is updating a database table without a requiring a query and a second round trip to the server.
Because [!INCLUDEssNoVersion] doesn't support pseudo columns for identifiers, updates that have to use the autogenerated key feature must operate against a table that contains an IDENTITY column. [!INCLUDEssNoVersion] allows only a single IDENTITY column per table. The result set that is returned by getGeneratedKeys method of the SQLServerStatement class will have only one column, with the returned column name of GENERATED_KEYS. If generated keys are requested on a table that has no IDENTITY column, the JDBC driver will return a null result set.
As an example, create the following table in the [!INCLUDEssSampleDBnormal] sample database:
CREATE TABLE TestTable
(Col1 int IDENTITY,
Col2 varchar(50),
Col3 int);
In the following example, an open connection to the [!INCLUDEssSampleDBnormal] sample database is passed in to the function, a SQL statement is constructed that will add data to the table, and then the statement is run and the IDENTITY column value is displayed.
[!codeJDBC#UsingAutoGeneratedKeys1]