jdbc access to just auto-generated primary key

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 JDBC Database Programming with J2EE This book, then I think enough of all of the above talk about how to obtain a new record no automatic generation of primary key, on-line had not seized, I thought no way, and some time ago to write api document jdbc courseware to see only found in related support, special published this article and give the students just getting started reminder.

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);
分类:Java 时间:2010-03-29 人气:428
分享到:
blog comments powered by Disqus

相关文章

iOS 开发

Android 开发

Python 开发

JAVA 开发

开发语言

PHP 开发

Ruby 开发

搜索

前端开发

数据库

开发工具

开放平台

Javascript 开发

.NET 开发

云计算

服务器

Copyright (C) codeweblog.com, All Rights Reserved.

CodeWeblog.com 版权所有 黔ICP备15002463号-1

processed in 0.499 (s). 13 q(s)