Java jdbc 事务

Java jdbc 事务主要是要分两步操作

  • 事务自动提交关闭 conn.setAutoCommit(false);
  • 操作插入或更新数据
  • 提交事务 conn.commit();
  • 异常时 conn.rollback();

例子如下

package com.pangugle.test;

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

public class TestJDBC {

	public static Connection getConnect() throws ClassNotFoundException, SQLException
	{
		// 通过的反射的方式,导入数据库连接驱动
		Class.forName("com.mysql.jdbc.Driver");
		String url = "jdbc:mysql://192.168.3.201:3306/testpgdb??useUnicode=true&characterEncoding=utf8&jdbcCompliantTruncation=false&useSSL=false&tinyInt1isBit=false";
		Connection conn = DriverManager.getConnection(url, "root", "root");
		System.out.println("connect mysql is success ? " + !conn.isClosed());
		return conn;
	}

	public void testTranction(String username, String password) throws ClassNotFoundException, SQLException
	{
		Connection conn = getConnect();

		PreparedStatement ps = null;
		try {
			String sql = "update pangugle_user set user_password = ? where user_name = ?";
			ps = conn.prepareStatement(sql);
			ps.setString(1, password);
			ps.setString(2, username);

			conn.setAutoCommit(false);

			int rs = ps.executeUpdate();
			System.out.println("update 结果为 = " + rs);

			conn.commit();
		} catch (Exception e) {
			e.printStackTrace();

			conn.rollback();
		}
		finally
		{
			// 一定要关闭资源(当然我们还有一种技术,叫做连接池技术,就不在需要我们来关闭了)
			ps.close();
			conn.close();
		}
	}

	public static void main(String[] args) throws ClassNotFoundException, SQLException
	{
		// getConnect();

		//testInsert("u1", "p1");
		//testInsert("u2", "p2");
		//testInsert("u3", "p3");

		//testDelete("u1");

		testTranction("u2", "p2222");

	}
}

当然Java 这种事务在实际应用过程不是这样用的,而是会借用框架来操作,如