sql批处理

有时候,需要批量执行sql语句,例如批量保存数据等。

批处理特点:
   批处理的SQL语句的主题必须一样,不同的是批处理中的占位符的值。


注意事项:

    使用批处理的时候,如果一次执行的记录数过多,最好按10条或者100条执行一次操作,并清空批处理,这样做主要是为了避免内存溢出。


批处理相关方法

         |-- Statement

                  void addBatch(String sql)     添加批处理

                  void clearBatch()            清空批处理(PreparedStatement接口里面的方法)

                  int[] executeBatch()         执行批处理

         |--PreparedStatement

                  void addBatch()              添加批处理


测试批处理Batch.java

package com.cn.statement;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.ArrayList;

import org.junit.Test;

import com.cn.Util.JdbcUtil;
import com.cn.entity.User;

public class Batch {
	/**
	 * 测试批处理
	 * @throws Exception
	 */
	@Test
	public void testBatch(){
		
		Connection conn = null;
		PreparedStatement pstmt = null;
		
		//准备参数
		ArrayList<User> list = new ArrayList<User>();
		list.add(new User("小李", "1234"));
		list.add(new User("吴莫愁", "4444"));
		
		try {
			//获取连接对象
			conn = JdbcUtil.getConnection();
			//准备sql
			String sql = "insert into users(name, password) values(?,?)";
			//预编译sql
			pstmt = conn.prepareCall(sql);
			//设置参数
			for(int i=0; i<list.size(); i++){
				User user = list.get(i);
				pstmt.setString(1, user.getName());
				pstmt.setString(2, user.getPassword());
				
				pstmt.addBatch();//将给定的 SQL 命令添加到此 Statement 对象的当前命令列表中。不需要传入sql
				
				if(i%5 == 0){
					pstmt.executeBatch();//执行批处理
					pstmt.clearBatch();//空此 Statement 对象的当前 SQL 命令列表。
				}
			}
			pstmt.executeBatch();//执行批处理
			pstmt.clearBatch();//空此 Statement 对象的当前 SQL 命令列表。
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}finally{
			JdbcUtil.close(conn, pstmt);
		}
	}
}

User.java

package com.cn.entity;

public class User {
	private String name;
	private String password;
	public User() {
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public User(String name, String password) {
		super();
		this.name = name;
		this.password = password;
	}
	
}

JdbcUtil.java

package com.cn.Util;

import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * jdbc的工具类
 * @author liuzhiyong
 *
 */
public class JdbcUtil {
	private static String url = null;
	private static String user = null;
	private static String password = null;
	private static String driverClass = null;
	
	/**
	 * 静态代码块(只调用一次)
	 */
	static{
		try {
			//读取db.properties文件
			Properties properties = new Properties();
			/**
			 * 
			 * 加载文件
			 * 
			 *  . 代表java的命令运行的目录
			 *  在java项目下,  . java命令的运行目录从项目的根目录MyEclipse工作空间/bin 目录开始
			 *  在web项目下, . java命令的运行目录从tomact/bin 目录开始
			 *  所以不能用.
			 */
			
			/**
			 * 使用类路径的读取方式
			 * 	/  斜杠表示classpath的根目录
			 * 在java项目下,classpath的根目录从bin目录开始
			 * 在web项目下,classpath的根目录从WEB-INF/classes目录开始
			 */
			InputStream in = JdbcUtil.class.getResourceAsStream("/db.properties");
			properties.load(in);
			//读取信息
			url = properties.getProperty("url");
			user = properties.getProperty("user");
			password = properties.getProperty("password");
			driverClass = properties.getProperty("driverClass");
			System.out.println(url);
			System.out.println(user);
			System.out.println(password);
			System.out.println(driverClass);
			//注册驱动程序
			Class.forName(driverClass);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("驱动程序注册出错!");
		}
	}
	
	/**
	 * 获取连接对象的方法
	 */
	public static Connection getConnection(){
		
		try {
			Connection conn = DriverManager.getConnection(url, user, password);
			return conn;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}

	/**
	 * 释放资源的重载方法
	 */
	public static void close(Connection conn, Statement stmt, ResultSet rs){
		
		//关闭资源(顺序:后打开,先关闭)
		if(rs != null){
			try {
				rs.close();
			} catch (SQLException e) {
				System.out.println("ResultSet关闭失败!");
				throw new RuntimeException(e);
			}
		}if(stmt != null){
			try {
				stmt.close();
			} catch (SQLException e) {
				System.out.println("Statement关闭失败!");
				throw new RuntimeException(e);
			}
		}
		if(conn != null){
			try {
				conn.close();
			} catch (SQLException e) {
				System.out.println("Connection关闭失败!");
				throw new RuntimeException(e);
			}
		}
	}
	
	/**
	 * 释放资源的重载方法
	 */
	public static void close(Connection conn, Statement stmt){
		
		//关闭资源(顺序:后打开,先关闭)
		if(stmt != null){
			try {
				stmt.close();
			} catch (SQLException e) {
				System.out.println("Statement关闭失败!");
				throw new RuntimeException(e);
			}
		}
		if(conn != null){
			try {
				conn.close();
			} catch (SQLException e) {
				System.out.println("Connection关闭失败!");
				throw new RuntimeException(e);
			}
		}
	}
	
}
数据插入成功:
 
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值