八、JDBC批量处理sql语句

业务场景:
当需要向数据库发送一批 SQL 语句执行时,应避免向数据库一条条的发送执行,而应采用 JDBC 的批处理机制,以提升执行效率。
实现批处理的第一种方式
采用如下方法:
Statement.addBatch(sql)
执行批处理 SQL 语句
executeBatch() 方法:执行批处理命令

clearBatch()方法:清除批处理命令


优点: 可以向数据库发送多条不同的SQL语句。
缺点:
SQL 语句没有预编译。
当向数据库发送多条语句相同,但仅参数不同的 SQL 语句时,需重复写上很多条 SQL 语句。例如:
Insert into user(name,password) values( aa , 111 );
Insert into user(name,password) values( bb , 222 );
Insert into user(name,password) values( cc , 333 );
Insert into user(name,password) values( dd , 444 );
实现批处理的第二种方式
采用 PreparedStatement.addBatch() 方法执行。

优点: 可以通过占位符预编译,简化了重复属性多条格式相同的语句。
缺点: 执行批处理的时候只能执行同一格式类型的语句,不能混合其他语句同时执行

下面写了个一个demo关于如何批量操作的演示:
package demo4;

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

import utils.JdbcUtils;

public class BatchTest {
	public static void main(String[] args) {
		//testStatement();
		 testPreparedStatement();
	}
        //方式1
	private static void testStatement() {
		Connection conn = JdbcUtils.getConnection();
		Statement stmt = null;
		if (null != conn) {
			try {
				stmt = conn.createStatement();
				//1.定义sql语句
				String sql1 = "create table if not exists book(id int primary key auto_increment," 
                                                + "name varchar(20),"
                                                + "price double);";
				String sql2 = "insert into book values(null,'三国演义2',50);";
				String sql3 = "insert into book values(null,'红楼梦2',52);";
				
				//2.添加要执行的任意类型的sql语句到批处理
				stmt.addBatch(sql1);
				stmt.addBatch(sql2);
				stmt.addBatch(sql3);
			
				//3.执行批处理
				stmt.executeBatch();
				
			} catch (SQLException e) {
				e.printStackTrace();
			} finally {
				JdbcUtils.release(null, stmt, conn);
			}
		}
	}
        //方式2
	private static void testPreparedStatement() {
		Connection conn = JdbcUtils.getConnection();
		PreparedStatement stmt = null;
		if (null != conn) {
			try {
				stmt = conn.prepareStatement("insert into book values(null,?,?)");
				// 1.通过stmt替换占位符
				for (int i = 1; i <= 120; i++) {
					stmt.setString(1, "新书" + i);
					stmt.setDouble(2, 50 + i);

					// 2.添加到batch中
					stmt.addBatch();
					
					// 3.执行批处理
					if (i % 50 == 0) {
						// 提高执行效率
						stmt.executeBatch();
						stmt.clearBatch();
					}
				}
				// 4.剩下的数据也需要执行批处理
				stmt.executeBatch();
			} catch (SQLException e) {
				e.printStackTrace();
			} finally {
				JdbcUtils.release(null, stmt, conn);
			}
		}
	}
}
JdbcUtils详情在这里的demo2

猜你喜欢

转载自blog.csdn.net/mchenys/article/details/80498640
今日推荐