Java 与数据库交互,如何实现事务

比如有个银行,当我进行转账的时候,却突然停电了,我的卡显示扣钱,但是转账的卡却没有增加相应的钱,这就需要实现事务了。
连接数据库的工具类:
utils:

package com.qf2002.utils;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/**
 * 2020/8/20
 * 16:31
 * 注册驱动
 * 获取连接
 * 增删查
 * 释放资源
 */
public class DbUtils {
   
    private static String driver;
    private static String url;
    private static String user;
    private static String password;
    //创建线程局部变量
    private static ThreadLocal<Connection> threadLocal;
    static{
   
        //注册驱动
        InputStream in = DbUtils.class.getClassLoader().getResourceAsStream("com/qf2002/utils/dbMessage.properties");
        Properties properties = new Properties();
        try {
   
            properties.load(in);
            driver = properties.getProperty("driver");
            url = properties.getProperty("url");
            user = properties.getProperty("user");
            password = properties.getProperty("password");
            threadLocal = new ThreadLocal<>();
        } catch (IOException e) {
   
            System.out.println("读取失败...");
        }finally {
   
            try {
   
                in.close();
            } catch (IOException e) {
   
                e.printStackTrace();
            }
        }
        try {
   
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
   
            System.out.println("驱动注册失败...");
        }
    }
    //得到连接
    public static Connection getConnect(){
   
        try {
   
            //判断线程局部变量中是否有连接
            Connection conn = threadLocal.get();
            if(conn==null){
   
                //如果没有,创造连接
                conn = DriverManager.getConnection(url, user, password);
                //放到线程局部变量中
                threadLocal.set(conn);
            }
            return conn;
        } catch (SQLException e) {
   
            e.printStackTrace();
        }
        return null;
    }
    //增删改
    public static int update(String sql,Object...objects) throws Exception{
   
        Connection conn = getConnect();
        PreparedStatement pstat = null;
        try {
   
            pstat = conn.prepareStatement(sql);
            for(int i=0;i<objects.length;i++){
   
                pstat.setObject(i+1, objects[i]);
            }
            return pstat.executeUpdate();
        }finally {
   
            shutAll(conn,pstat,null);
        }
    }

    //释放资源
    public static void shutAll(Connection conn, Statement stat, ResultSet res){
   
        try {
   
            if (res != null) {
   
                res.close();
            }
            if 
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值