方式一、批量执行预定义模式的SQLpublic static void exeBatch(Connection conn) { try {
String sql = "insert into t_example (code, name) values (?,?)" ;
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString( 1 , "java2" );
pstmt.setString( 2 , "java" );
//添加一次预定义参数
pstmt.addBatch();
pstmt.setString( 1 , "360sdn" );
pstmt.setString( 2 , "软件开发技术网" );
//再添加一次预定义参数
pstmt.addBatch();
//批量执行预定义SQL
pstmt.executeBatch();
} catch (SQLException e) {
e.printStackTrace();
} finally {
closeConnection(conn);
}
}
方式二、批量执行混合模式的SQL、有预定义的,还有静态的
public static void exeBatchMixedSQL( Connection conn) {
PreparedStatement pstmt = null ;
try {
String sql = "insert into t_example (code, name) values (?,?)" ;
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString( 1 , "java" );
pstmt.setString( 2 , "360sdn" );
//添加一次预定义参数
pstmt.addBatch();
pstmt.setString( 1 , "360sdn" );
pstmt.setString( 2 , "软件开发技术网" );
//再添加一次预定义参数
pstmt.addBatch();
//添加一次静态SQL
pstmt.addBatch( "update t_example set code= '360.com' where code='360sdn'" );
//批量执行预定义SQL
pstmt.executeBatch();
} catch (SQLException e) {
e.printStackTrace();
} finally {
closeConnection(conn);
}
}
方式三、执行批量静态的SQL //执行批量静态的SQL
ublic static void exeBatchSQL(Connection conn) {
try {
Statement stmt = conn.createStatement();
//连续添加多条静态SQL
stmt.addBatch( "insert into t_example (code, name) values ('java', '360sdn.com')" );
stmt.addBatch( "insert into t_example (code, name) values ('360', '360sdn')" );
stmt.addBatch( "delete from t_example where code='java'" );
stmt.addBatch( "update t_example set kind = '360data' where kind='360'" );
//批量执行不支持Select语句
// stmt.addBatch("select count(*) from t_example");
//执行批量执行
stmt.executeBatch();
} catch (SQLException e) {
e.printStackTrace();
} finally {
closeConnection(conn);
}
}
|