用jdbc管理事务

用jdbc管理简单的事务,该代码已经用自己定义的工具类简化了

package hj.jdbc;

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

/**
 * jdbc管理事务
 */
public class day5 {
    public static void main(String[] args) {
        Connection getconnection=null;
        PreparedStatement preparedStatement =null;
        PreparedStatement preparedStatement1=null;
        try {
             getconnection = jdbcutils.getconnection();
            getconnection.setAutoCommit(false);
            //在执行sql语句之前开启事务
            String sql="update dd set id=id-? where name=?";
            String sql1="update dd set id=id+? where name=?";

             preparedStatement = getconnection.prepareStatement(sql);
             preparedStatement1 = getconnection.prepareStatement(sql1);
            preparedStatement.setInt(1,134);

              preparedStatement.setString(2,"张三");

            preparedStatement1.setInt(1,13);
            preparedStatement1.setString(2,"l李四");
            preparedStatement.executeUpdate();
            preparedStatement1.executeUpdate();
            getconnection.commit();//执行完所有sql语句后提交事务
        } catch (Exception e) {
            try {if (getconnection!=null)
                getconnection.rollback();//在出现异常时回滚事务
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
        }finally {
            jdbcutils.close3(preparedStatement,getconnection);
           jdbcutils.close3(preparedStatement1,null);
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值