java JDBC 进行sql语句的批处理的两种方法示例代码。表是oracle数据库里的dept表,为了看清逻辑关系,把异常都throws 出去。
1 package com.ayang.jdbc; 2 3 import java.sql.*; 4 5 6 public class TestBatch { 7 8 //为看清逻辑关系,throws出去 9 public static void main(String[] args) throws Exception { 10 Class.forName("oracle.jdbc.driver.OracleDriver"); 11 Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1521:ORCL","scott","root"); 12 13 /** 14 * 批处理 方法一: 15 */ 16 /*Statement stmt = conn.createStatement(); 17 stmt.addBatch("insert into dept2 values(51,‘JAVA‘,‘XC‘)"); 18 stmt.addBatch("insert into dept2 values(52,‘PHP‘,‘ZZ‘)"); 19 stmt.addBatch("insert into dept2 values(53,‘C++‘,‘XINYANG‘)"); 20 21 stmt.executeBatch(); 22 stmt.close();*/ 23 24 /** 25 * 批处理 方法二: 26 */ 27 PreparedStatement ps = conn.prepareStatement("insert into dept2 values(?,?,?)"); 28 ps.setInt(1, 54); 29 ps.setString(2, "haha"); 30 ps.setString(3, "HangZhou"); 31 ps.addBatch(); 32 33 ps.setInt(1, 55); 34 ps.setString(2, "haha"); 35 ps.setString(3, "HangZhou"); 36 ps.addBatch(); 37 38 ps.setInt(1, 56); 39 ps.setString(2, "haha"); 40 ps.setString(3, "HangZhou"); 41 ps.addBatch(); 42 ps.executeBatch(); 43 ps.close(); 44 45 conn.close(); 46 47 } 48 49 }
时间: 2024-10-23 23:01:00