java.sql.Connection接口提供了三个在执行插入语句后可取的自动生成的主键的方法。
2 |
PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException;
|
3 | 其中autoGenerateKeys 有两个可选值:Statement.RETURN_GENERATED_KEYS、Statement.NO_GENERATED_KEYS |
5 |
PreparedStatement prepareStatement(String sql, int [] columnIndexes) throws SQLException;
|
7 |
PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLEception;
|
02 |
public int [] insert(List<Person> persons) throws SQLException{
|
03 |
String sql = "insert into test_table(name) values(?)" ;
|
05 |
int rowCount = persons.size() ;
|
06 |
int [] keys = new int [rowCount] ;
|
07 |
DataSource ds = SimpleDBSource.getDB() ;
|
08 |
Connection conn = ds.getConnection() ;
|
10 |
String[] columnNames= { "id" } ;
|
11 |
PreparedStatement pstmt = conn.prepareStatement(sql, columnNames) ;
|
13 |
for (i = 0 ; i < rowCount ; i++){
|
15 |
pstmt.setString( 1 , p.getName()) ;
|
18 |
pstmt.executeBatch() ;
|
20 |
ResultSet rs = pstmt.getGeneratedKeys() ;
|
21 |
while (rs.next() && i < rowCount){
|
22 |
keys[i] = rs.getInt( 1 ) ;
|