用JDBC3 安插记录返回自动生成的主键
java.sql.Connection接口提供了三个在执行插入语句后可取的自动生成的主键的方法。
1
//第一个是
2
PreparedStatement prepareStatement(String sql,
int
autoGeneratedKeys)
throws
SQLException;
3
其中autoGenerateKeys 有两个可选值:Statement.RETURN_GENERATED_KEYS、Statement.NO_GENERATED_KEYS
4
//第二个是
5
PreparedStatement prepareStatement(String sql,
int
[] columnIndexes)
throws
SQLException;
6
//第三个是
7
PreparedStatement prepareStatement(String sql, String[] columnNames)
throws
SQLEception;
01
//批量插入Person实例,返回每条插入记录的主键值
02
public
int
[] insert(List<Person> persons)
throws
SQLException{
03
String sql =
"insert into test_table(name) values(?)"
;
04
int
i =
0
;
05
int
rowCount = persons.size() ;
06
int
[] keys =
new
int
[rowCount] ;
07
DataSource ds = SimpleDBSource.getDB() ;
08
Connection conn = ds.getConnection() ;
09
//根据主键列名取得自动生成主键值
10
String[] columnNames= {
"id"
} ;
11
PreparedStatement pstmt = conn.prepareStatement(sql, columnNames) ;
12
Person p =
null
;
13
for
(i =
0
; i < rowCount ; i++){
14
p = persons.get(i) ;
15
pstmt.setString(
1
, p.getName()) ;
16
pstmt.addBatch();
17
}
18
pstmt.executeBatch() ;
19
//取得自动生成的主键值的结果集
20
ResultSet rs = pstmt.getGeneratedKeys() ;
21
while
(rs.next() && i < rowCount){
22
keys[i] = rs.getInt(
1
) ;
23
i++ ;
24
}
25
return
keys ;
26
}