两种方式完成批处理的优缺点

一、采用Statement实现批处理

  1. 使用Statement 对象添加要批量执行sql语句(如下)
 Statement.addBatch(sql1);
 Statement.addBatch(sql2);
 Statement.addBatch(sql3);
  1. 执行批处理Sql语句:Statement.executeBath();
  2. 清除批处理命令:Statement.clearBatch();

 

  • 优点:可以向数据库发送多条不同的SQL语句
  • 缺点:SQL语句没有预编译
  • 当向数据库发送多条语句相同,但仅参数不同的SQL语句时。需重复写上很多条SQL语句。

测试代码如下:

package jdbc;

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

import com.mysql.jdbc.Driver;

/*
 * statement 批处理
 * 
*/

public class StatementBatch {
	public static void main(String[] args) throws Exception {
		//加载驱动
		Class.forName("com.mysql.jdbc.Driver");
		//获取连接
		//创建Statement
		Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mybase","root","root123");
		System.out.println("你好啊"+conn);
		Statement stm = conn.createStatement();
		String sql1 = "insert into test(ename,job,deptno) values('小龙人','clerk',20)";
		String sql2 = "insert into test(ename,job,deptno) values('美人鱼','leader',10)";
		String sql3 = "update test set ename = '小龙人1' where ename = '小龙人'";
		//添加批处理
		stm.addBatch(sql1);
		stm.addBatch(sql2);
		stm.addBatch(sql3);
		//执行批处理
		stm.executeBatch();
		//清楚批处理SQL
		stm.clearBatch();
		//释放资源
		stm.close();
		conn.close();		
	}
}

 

二、采用PreparedStatement.addBatch() 实现批处理

优点:发送的是预编译后的SQL语句,执行效率高。

缺点:只能应用在SQL语句相同,但参数不同的批处理中。因此此种形式的批处理经常用于在同一个表中插入数据,或批量更新表的数据。

 测试代码如下:

package jdbc;

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

public class TestPreparedStatementbatch {

	public static void main(String[] args) throws Exception {
		//加载驱动
		Class.forName("com.mysql.jdbc.Driver");
		//获取连接
		Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mybase", "root", "root123");
		System.out.println(conn);
		//创建PreparedStatement对象
		String sql = "insert into test( empno, ename) values(?,?)";
		PreparedStatement pstm = conn.prepareStatement(sql);
		//pstm 绑定数据
		for(int i= 4020;i<4080;i++){
			pstm.setInt(1, i);
			pstm.setString(2, "蒋静"+i);
			//添加批处理
			pstm.addBatch();
			//执行批处理,当i是100的倍数时,执行,执行完清除掉
			if(i%100==0){
				pstm.executeBatch();
				pstm.clearBatch();
			}
		}
		//将批处理余下的语句执行完毕
		pstm.executeBatch();
		//释放资源
		pstm.close();
		conn.close();
	}

}

 三、小结

搭配着使用就完了呗。

猜你喜欢

转载自blog.csdn.net/weixin_44146025/article/details/107678550