jdbc 执行批量操作

package com.dada.test;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.Statement;

public class TestBatch {
	public static void main(String[] args) throws Exception {
//		insertByPreparedStatement();
		insertByBatchStat();
//		insertByStat();
	}
	
	public static Connection getConnection() {
		Connection conn = null;
		try {
			Class.forName("com.mysql.jdbc.Driver");
			String url = "jdbc:mysql://localhost:3306/test?characterEncoding=utf-8";
			conn= DriverManager.getConnection(url, "root", "test");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return conn;
	}
	
	/**
	 * 通过PreparedStatement执行batch
	 * @throws Exception
	 */
	public static void insertByPreparedStatement() throws Exception {
		Connection conn  = getConnection();
		conn.setAutoCommit(false);
		String sql = "insert into test(id,name) values(?,?)";
		PreparedStatement ps = conn.prepareStatement(sql);
		
		try{
			for(int i=1;i<10;i++) {
//				如果要为某个字段赋予空值,就使用下面的方法,而这个地方也
//				ps.setNull(4,Types.CHAR);
				ps.setInt(1, i);
				ps.setString(2, "test"+i);
				ps.addBatch();
			}
			ps.executeBatch();
			conn.commit();
		} catch(Exception e) {
			try{
				conn.rollback();
			}catch(Exception e1) {
				e1.printStackTrace();
			}
			e.printStackTrace();
		} finally {
			try{
				ps.close();
				conn.close();
			}catch(Exception e) {
				e.printStackTrace();
			}
		}
 	}
	
	/**
	 * 使用批量插入
	 * @throws Exception
	 */
	public static void insertByBatchStat() throws Exception {
		Connection conn  = getConnection();
		conn.setAutoCommit(false);
		Statement ps = conn.createStatement();
		
		try{
			for(int i=1;i<10;i++) {
				ps.addBatch("insert into test(id,name) values("+i+",'test"+i+"')");
			}
			ps.executeBatch();
			conn.commit();
		} catch(Exception e) {
			try{
				conn.rollback();
			}catch(Exception e1) {
				e1.printStackTrace();
			}
			e.printStackTrace();
		} finally {
			try{
				ps.close();
				conn.close();
			}catch(Exception e) {
				e.printStackTrace();
			}
		}
 	}
	
	/**
	 * 直接用Statement插入
	 * @throws Exception
	 */
	public static void insertByStat() throws Exception {
		Connection conn  = getConnection();
		conn.setAutoCommit(false);
		Statement ps = conn.createStatement();
		
		try{
			for(int i=1;i<10;i++) {
				ps.execute("insert into test(id,name) values("+i+",'test"+i+"')");
			}
			ps.executeBatch();
			conn.commit();
		} catch(Exception e) {
			try{
				conn.rollback();
			}catch(Exception e1) {
				e1.printStackTrace();
			}
			e.printStackTrace();
		} finally {
			try{
				ps.close();
				conn.close();
			}catch(Exception e) {
				e.printStackTrace();
			}
		}
 	}
}

你可能感兴趣的:(jdbc 执行批量操作)