spring利用jdbctemplate实现批量插入怎么存储时间
1个回答
展开全部
1、先介绍一下java.sql.Connection接口提供的三个在执行插入语句后可取的自动生成的主键的方法:
复制代码
//第一个是
PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException;
其中autoGenerateKeys 有两个可选值:Statement.RETURN_GENERATED_KEYS、Statement.NO_GENERATED_KEYS
//第二个是
PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException;
//第三个是
PreparedStatement prepareStatement(String sql, String[] columnNames)throws SQLEception;
复制代码
复制代码
//批量插入Person实例,返回每条插入记录的主键值
public int[] insert(List<Person> persons) throws SQLException{
String sql = "insert into test_table(name) values(?)" ;
int i = 0 ;
int rowCount = persons.size() ;
int[] keys = new int[rowCount] ;
DataSource ds = SimpleDBSource.getDB() ;
Connection conn = ds.getConnection() ;
//根据主键列名取得自动生成主键值
String[] columnNames= {"id"} ;
PreparedStatement pstmt = conn.prepareStatement(sql, columnNames) ;
Person p = null ;
for (i = 0 ; i < rowCount ; i++){
p = persons.get(i) ;
pstmt.setString(1, p.getName()) ;
pstmt.addBatch();
}
pstmt.executeBatch() ;
//取得自动生成的主键值的结果集
ResultSet rs = pstmt.getGeneratedKeys() ;
while(rs.next() && i < rowCount){
keys[i] = rs.getInt(1) ;
i++ ;
}
return keys ;
}
复制代码
复制代码
//第一个是
PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException;
其中autoGenerateKeys 有两个可选值:Statement.RETURN_GENERATED_KEYS、Statement.NO_GENERATED_KEYS
//第二个是
PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException;
//第三个是
PreparedStatement prepareStatement(String sql, String[] columnNames)throws SQLEception;
复制代码
复制代码
//批量插入Person实例,返回每条插入记录的主键值
public int[] insert(List<Person> persons) throws SQLException{
String sql = "insert into test_table(name) values(?)" ;
int i = 0 ;
int rowCount = persons.size() ;
int[] keys = new int[rowCount] ;
DataSource ds = SimpleDBSource.getDB() ;
Connection conn = ds.getConnection() ;
//根据主键列名取得自动生成主键值
String[] columnNames= {"id"} ;
PreparedStatement pstmt = conn.prepareStatement(sql, columnNames) ;
Person p = null ;
for (i = 0 ; i < rowCount ; i++){
p = persons.get(i) ;
pstmt.setString(1, p.getName()) ;
pstmt.addBatch();
}
pstmt.executeBatch() ;
//取得自动生成的主键值的结果集
ResultSet rs = pstmt.getGeneratedKeys() ;
while(rs.next() && i < rowCount){
keys[i] = rs.getInt(1) ;
i++ ;
}
return keys ;
}
复制代码
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询