JDBC简介(批量处理与事务处理)

时间:2022-05-30 12:02:52

范例:执行批处理

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

public class OracleDemo {
	private static final String DBDRIVER = "oracle.jdbc.driver.OracleDriver";
	private static final String DBURL = "jdbc:oracle:thin:@localhost:1521:acehzh";
	private static final String USER = "scott";
	private static final String PASSWORD = "tiger";

	public static void main(String[] args) throws Exception {
		// 1.加载数据库驱动
		Class.forName(DBDRIVER);
		// 2.链接数据库
		Connection conn = DriverManager.getConnection(DBURL, USER, PASSWORD);
		// 3.操作数据库
		Statement sta = conn.createStatement();
		sta.addBatch("INSERT INTO member(mid,name) VALUES(myseq.nextval,'测试员A')");
		sta.addBatch("INSERT INTO member(mid,name) VALUES(myseq.nextval,'测试员B')");
		sta.addBatch("INSERT INTO member(mid,name) VALUES(myseq.nextval,'测试员C')");
		sta.addBatch("INSERT INTO member(mid,name) VALUES(myseq.nextval,'测试员D')");
		int[] result = sta.executeBatch();
		System.out.println(Arrays.toString(result));
		conn.close();
	}

}

==============分割线===============

范例2:利用事务处理

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

public class OracleDemo {
	private static final String DBDRIVER = "oracle.jdbc.driver.OracleDriver";
	private static final String DBURL = "jdbc:oracle:thin:@localhost:1521:acehzh";
	private static final String USER = "scott";
	private static final String PASSWORD = "tiger";

	public static void main(String[] args) throws Exception {
		// 1.加载数据库驱动
		Class.forName(DBDRIVER);
		// 2.链接数据库
		Connection conn = DriverManager.getConnection(DBURL, USER, PASSWORD);
		// 3.操作数据库
		Statement sta = conn.createStatement();
		conn.setAutoCommit(false);
		try {			
			sta.addBatch("INSERT INTO member(mid,name) VALUES(myseq.nextval,'测试员A')");
			sta.addBatch("INSERT INTO member(mid,name) VALUES(myseq.nextval,'测试员B')");
			sta.addBatch("INSERT INTO member(mid,name) VALUES(myseq.nextval,'测试员C')");
			sta.addBatch("INSERT INTO member(mid,name) VALUES(myseq.nextval,'测试员D')");
			int[] result = sta.executeBatch();
			System.out.println(Arrays.toString(result));
			conn.commit();//如果没有错误就会提交
		} catch (Exception e) {
			e.printStackTrace();
			conn.rollback();
		}
		
		conn.close();
	}
JDBC简介(批量处理与事务处理)