Java JDBC基础(五)

6 篇文章 0 订阅

 1.JDBC批处理

 

package com.yli.demo;

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

/**
 * 简单批处理测试
 * @author yli
 *
 */
public class BatchTest {

	public static void main(String[] args) {
		// Test1();
		Test2();
	}

	/**
	 * 非事务测试<br>
	 * 批处理操作不能包含查询SQL,否则会抛出异常<br>
	 * 批处理返回的结果是整型数组,表示每一条SQL语句执行成功后受影响的记录条数
	 */
	public static void Test1() {
		try {
			Connection conn;
			conn = ConnectionUtil.getConnection();

			String sql = "update es_t_shop_affiche set affichetitle='admin' where afficheid=100001";
			Statement stat = conn.createStatement();
			stat.addBatch(sql);

			sql = "update es_t_shop_affiche set affichetitle='root' where afficheid=100002";
			stat.addBatch(sql);

			int[] count = stat.executeBatch();
			for (int i = 0; i < count.length; i++) {
				System.out.println(count[i]);
			}
			
			ConnectionUtil.close(conn);

		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 批处理操作必须视为一个事务
	 */
	public static void Test2() {
		try {
			Connection conn;
			conn = ConnectionUtil.getConnection();
			boolean autoCommit = conn.getAutoCommit();
			conn.setAutoCommit(false);

			String sql = "update es_t_shop_affiche set affichetitle='aaa' where afficheid=100001";
			Statement stat = conn.createStatement();
			stat.addBatch(sql);

			sql = "update es_t_shop_affiche set affichetitle='bbb' where afficheid=100002";
			stat.addBatch(sql);

			int[] count = stat.executeBatch();
			for (int i = 0; i < count.length; i++) {
				System.out.println(count[i]);
			}
			
			conn.commit();
			// 将是否自动提交属性还原
			conn.setAutoCommit(autoCommit);
			
			ConnectionUtil.close(conn);

		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

}

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值