JDBC 批处理

JDBC 批处理

前言

JDBC 批处理查询/新增/修改的使用。虽然在一般的编码中不会直接使用jdbc的批处理,但是作为了解记录下来。

编码记录

JDBC批处理的使用

package org.xqlee.utils.database;

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

/**
 * 
 * 
 * <pre>
 * _________________________INFO_____________________________
 * | Description : [JDBC批处理的使用] 
 * | Encoding    : [UTF-8]
 * | Package     : [org.xqlee.utils.database]
 * | Project     : [utils]
 * | Author      : [LXQ]
 * | CreateDate  : [2016年6月7日上午9:57:33]
 * | Updater     : []
 * | UpdateDate  : []
 * | UpdateRemark: []
 * | Company     : [Shallink Electronic Information]
 * | Version     : [v 1.0]
 * | Libs        : []
 * __________________________________________________________
 * </pre>
 */
public class BatchSQL {

	public static void main(String[] params) {

		// statementBatch();
		preparedStatementBatch();
	}

	/**
	 * @说明 采用statement方式,不进行预编译 <BR/>
	 * @优点 能针对不同类型的sql语句进行批处理<BR/>
	 * @缺点 语句没进行预编译
	 * @场景 执行多条不同的sql语句,如新增,更新同时进行的情况
	 */
	public static void statementBatch() {
		Connection conn = null;
		Statement st = null;
		try {
			// 得到数据库连接
			conn = new DBManager("test").getConnection();
			conn.setAutoCommit(false);
			st = conn.createStatement();
			String sql = "";
			sql = "insert into test_batch values('1111','2222','33333')";
			st.addBatch(sql);
			sql = "insert into test_batch values('1111','4444','4444')";
			st.addBatch(sql);
			sql = "update test_batch set a='0000'";
			st.addBatch(sql);
			st.executeBatch();
			conn.commit();
			st.clearBatch();

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (st != null) {
					st.close();
					st = null;
				}
				if (conn != null) {
					conn.close();
					conn = null;
				}
			} catch (Exception e2) {
				// 忽略
			}
		}

	}

	/**
	 * @说明 采用PreparedStatement进行预编译的方式执行批处理<BR/>
	 * @优势 采用了预编译sql,执行效率高<BR/>
	 * @缺点 只能处理sql语句相同但参数不同的批处理当中<BR/>
	 * @场景 批量新增,批量更新
	 */
	public static void preparedStatementBatch() {
		Connection conn = null;
		PreparedStatement ps = null;
		try {
			// 得到数据库连接
			conn = new DBManager("test").getConnection();
			conn.setAutoCommit(false);
			String sql = "insert into test_batch values(?,?,?)";
			ps = conn.prepareStatement(sql);
			for (int i = 0; i < 10; i++) {
				ps.setString(1, i + "A");
				ps.setString(2, i + "B");
				ps.setString(3, i + "C");
				ps.addBatch();
			}
			ps.executeBatch();
			conn.commit();
			ps.clearBatch();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (null != ps) {
					ps.close();
					ps = null;
				}
				if (null != conn) {
					conn.close();
					conn = null;
				}
			} catch (Exception e2) {
				// 忽略
			}

		}

	}

}
JDBC 批处理

相关文章:

你感兴趣的文章:

标签云: