1.使用addBatch方法添加DML语句;
2.使用executeBatch方法提交批处理语句。
实例:
TestBatch.java:
- import java.sql.*;
- public class TestBatch {
- public static void main(String[] args) {
- Connection conn = null;
- PreparedStatement pstmt = null;
- try {
- Class.forName("oracle.jdbc.driver.OracleDriver");
- conn = DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1521:mgc","system","admin");
- String sql = "Insert INTO member(id,name) VALUES(?,?)";
- pstmt = conn.prepareStatement(sql);
- pstmt.setInt(1, 12);
- pstmt.setString(2, "n12");
- pstmt.addBatch();
- pstmt.setInt(1, 13);
- pstmt.setString(2, "n13");
- pstmt.addBatch();
- pstmt.setInt(1, 14);
- pstmt.setString(2, "n14");
- pstmt.addBatch();
- pstmt.executeBatch();
- } catch (ClassNotFoundException e) {
- e.printStackTrace();
- } catch (SQLException e) {
- e.printStackTrace();
- } finally {
- try {
- if (pstmt != null) {
- pstmt.close();
- pstmt = null;
- }
- if (conn != null) {
- conn.close();
- conn = null;
- }
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
- }
- }