His school days to a company to site, encountered a small problem: how to obtain the record just inserted automatically generated primary key.
For example I would like to generate an order, you will need to insert a record in Table 2: "Order Form" and "commodity items" ( "commodity items" to "Order Form" of the primary key as foreign key).
I was very clumsy way, insert the record, according to the record number of conditions, the primary key check out, Hehe;
But later, to avoid this problem, I should first get the primary key and then to insert, anyway, are stupid enough.
When I was looking to learn jdbc
We need to use the following two methods:
Connection interface defines methods
PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) Creates a default PreparedStatement object that gets automatically generated keys.
Statement interface defines methods
ResultSet getGeneratedKeys() Gets the object because execution of this Statement and create all the auto-generated keys.
The following table as an example:
CREATE TABLE userinfo( id int IDENTITY(1,1) PRIMARY KEY NOT NULL, name varchar(50) NULL )
java code to achieve:
String sql = "insert into userinfo values (' Smith, John ')"; PreparedStatement stmt = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); stmt.executeUpdate(); ResultSet rs = stmt.getGeneratedKeys(); int newid = 0; if(rs.next()) newid = rs.getInt(1);