JDBC事务操作

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

public class JDBC {

	// static final的常量:1.直接初始化;2.通过static代码块初始化
	private static final String url;
	private static final String user;
	private static final String password;
	private static final String driver;
	private static final String sql1 = "";
	private static final String sql2 = "";

	// 通过static代码块初始化常量也是可行的
	static {
		url = "";
		user = "";
		password = "";
		driver = "";
	}

	public void jdbc() {
		try {
			// 实例化驱动
			Class.forName(driver);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}

		Connection con = null;
		PreparedStatement ps1 = null;
		PreparedStatement ps2 = null;
		Savepoint savepoint = null;

		try {
			// 获取数据库连接
			con = DriverManager.getConnection(url, user, password);
			// 设置自动提交为false
			con.setAutoCommit(false);
			// 设置事务隔离级别
			con.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
			// 进行事务操作
			ps1 = con.prepareStatement(sql1);
			int rs1 = ps1.executeUpdate(sql1);

			// 设置保存点
			savepoint = con.setSavepoint("SavePoint1");

			ps2 = con.prepareStatement(sql2);
			int rs2 = ps2.executeUpdate(sql2);
			// 提交事务
			con.commit();
			// 设置事务自动提交为true
			con.setAutoCommit(true);
		} catch (SQLException e) {
			e.printStackTrace();
			try {
				if (savepoint == null) {
					// 事务回滚到保存点
					con.rollback(savepoint);
					// 再提交事务
					con.commit();
				} else {
					// 直接回滚
					con.rollback();
				}
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
		} finally {

			// 倒序关闭

			try {
				if (ps1 != null) {
					ps1.close();
				}
			} catch (SQLException e1) {
				e1.printStackTrace();
			}

			try {
				if (ps2 != null) {
					ps2.close();
				}
			} catch (SQLException e1) {
				e1.printStackTrace();
			}

			try {
				if (con != null) {
					con.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}

		}

	}
}

猜你喜欢

转载自yanguz123.iteye.com/blog/2232933