public class T {
public static void main(String[] args) throws Exception {
/**
* 事务练习,有回滚测试
*
* 结合了DButils应用
*
*/
Connection connection=null;
Statement statement=null;
ResultSet resultSet=null;
//QueryRunner qr=new QueryRunner(DruidTools.getDateSoure());
//System.out.println(qr);
try {
connection = DruidTools.getConnection();
connection.setAutoCommit(false);
statement = connection.createStatement();
String sql = "SELECT * FROM tb_account WHERE username='batMan' AND balance >=1000";
resultSet = statement.executeQuery(sql);
if (!resultSet.next()) {
throw new RuntimeException("fucker,you have no money!!");
}
String sql1 = "UPDATE tb_account set balance = balance-1000 WHERE username='batMan'";
int i = statement.executeUpdate(sql1);
//把注释去掉,则可以测试回滚功能
//System.out.println(i/0);
String sql2 = "UPDATE tb_account set balance = balance+1000 WHERE username='Joker'";
int i1 = statement.executeUpdate(sql2);
//提交事务
connection.commit();
}catch (Exception e){
e.printStackTrace();
connection.rollback(); //回滚操作
}finally {
DruidTools.close(connection,statement,resultSet);
}
}
}
//DButils工具类的封装
package com.day_1;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public class DruidTools {
private static Properties properties=new Properties();
private static DataSource dataSource;
static {
try {
//获取类加载器
ClassLoader classLoader=Thread.currentThread().getContextClassLoader();
//使用类加载器获取 项目类路径下的文件
InputStream inputStream=classLoader.getResourceAsStream("db.properties");
//使用Properties配置文件对挺的输入流
properties.load(inputStream);
//创建连接池对象
dataSource= DruidDataSourceFactory.createDataSource(properties);
}catch (Exception e){
e.printStackTrace();
}
}
public static DataSource getDateSoure(){
return dataSource;
}
public static Connection getConnection() throws Exception {
return dataSource.getConnection();
}
public static void close(Connection con, Statement sm, ResultSet rs){
try {
if (rs!=null){
rs.close();
}
}catch (Exception e){
e.printStackTrace();
}finally {
try {
if (sm!=null){
sm.close();
}
}catch (Exception e){
e.printStackTrace();
}finally {
try {
if (con!=null){
con.close();
}
}catch (Exception e){
e.printStackTrace();
}
}
}
}
}
学习过程15
最新推荐文章于 2021-12-15 15:02:19 发布