欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

数据库事务

程序员文章站 2023-12-23 11:37:10
...
package com.test;

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

public class TestTransaction {
	
	public static void main(String[] args) throws SQLException {
		
		Connection conn = null;
		Statement stmt = null;
		Savepoint sp = null;
		try{
			Class.forName("com.mysql.jdbc.Driver");
			conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/for117", "root", "admin");
			conn.setAutoCommit(false);
			stmt = conn.createStatement();
			stmt.executeUpdate("update  tb_test set number = number*2 where id = 1");
			sp =  conn.setSavepoint();
			stmt.executeUpdate("update  tb_test set number = number*2 where id = 2");
			int i = 34;
			int b = i*2;
			if(b>3){
				throw new Exception();
			}
			stmt.executeUpdate("update  tb_test set number = number*2 where id = 3");
			conn.commit();
		}catch (Exception e) {
		  conn.rollback(sp);
		  conn.commit();
		}
	}
}

上一篇:

下一篇: