class="java" name="code">import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.Statement; public class Test { public static Connection getConnection() { try { Class.forName("com.mysql.jdbc.Driver"); Connection con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/uc2", "root", ""); return con; } catch (Exception e) { e.printStackTrace(); } return null; } /** * 使用 Statement 执行批处理 * 批处理只能执行更新类SQL,类似 executeUpdate() */ public static void statementBatch(){ Connection con = getConnection(); Statement st = null; if(con != null){ try { st = con.createStatement(); st.addBatch("INSERT INTO uc_role (role_id, name, note, type ) VALUES ( 1, '1', '1', '1' )"); st.addBatch("INSERT INTO uc_role (role_id, name, note, type ) VALUES ( 2, '2', '2', '2' )"); st.addBatch("delete from uc_role where role_id in(1,2)"); int[] res = st.executeBatch(); for (int i = 0; i < res.length; i++) { //打印结果: 1 1 2 System.out.println(res[i]); } } catch (Exception e) { e.printStackTrace(); }finally{ //关闭 statement connection } } } /** * 使用 PreparedStatement 执行批处理 * 批处理只能执行更新类SQL,类似 executeUpdate() */ public static void preparedstatementBatch(){ Connection con = getConnection(); PreparedStatement pst = null; if(con != null){ try { pst = con.prepareStatement("INSERT INTO uc_role (role_id, name, note, type ) VALUES ( ?, ?, ?, ? )"); pst.setInt(1, 1); pst.setString(2, "角色1"); pst.setString(3, "note1"); pst.setString(4, "type1"); pst.addBatch(); pst.setInt(1, 11); pst.setString(2, "角色11"); pst.setString(3, "note11"); pst.setString(4, "type11"); pst.addBatch(); pst.addBatch("INSERT INTO uc_role (role_id, name, note, type ) VALUES ( 2, '2', '2', '2' )"); pst.addBatch("delete from uc_role where role_id in(1,11,2)"); int[] res = pst.executeBatch(); for (int i = 0; i < res.length; i++) { //打印结果: 1 1 1 3 System.out.println(res[i]); } } catch (Exception e) { e.printStackTrace(); }finally{ //关闭 preparedstatement connection } } } public static void main(String[] args) { statementBatch(); preparedstatementBatch(); } }
?