学习_Java_Base_JDBC_数据库事务回滚示例

在代码src文件夹下创建文件dbinfo.proparties 内容如下

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/jdbc_db
username=root
passwd=zf5732663

事务控制如下:主要是使用rollback函数

package com.zhaofei.jdbc.study;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class DButil {

	public Connection openConnection() {
		Properties prop = new Properties();
		String driver = null;
		String url = null;
		String username = null;
		String passwd = null;
		try {
			prop.load(this.getClass().getClassLoader()
					.getResourceAsStream("dbinfo.proparties"));
			driver = prop.getProperty("driver");
			url = prop.getProperty("url");
			username = prop.getProperty("username");
			passwd = prop.getProperty("passwd");
			Class.forName(driver);// 加载数据库驱动
			return DriverManager.getConnection(url, username, passwd);// 返回连接数据库的实例
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	public void closeConnection(Connection conn) {
		if (null != conn) {
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				
				e.printStackTrace();
			}
		}
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		DButil util = new DButil();
		util.add();
	}
	public void add() {
		DButil util = new DButil();
		String sql1 = "update AccountTbl set balance = balance - 1000 where name='tom'";
		String sql2 = "update AccountTbl set balance = balance + 1000 where name='kite'";
		Connection conn = util.openConnection();
		try {
			conn.setAutoCommit(false);
			Statement stmt = conn.createStatement();
			stmt.executeUpdate(sql1);
			stmt.executeUpdate(sql2);
			conn.commit();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			try {
				conn.rollback();
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			e.printStackTrace();
		}finally{
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值