package com.jdsc;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
/**
* @author Alina
* @date 2022年02月06日 2:51 下午
* 开启事务管理数据库,如果事务有异常则回滚到之前的状态
* JDBC控制事务:
* 1. 事务:一个包含多个步骤的业务操作。
* 需要被事务管理,同时成功,同时失败。
* 2. 操作:
* 开启事务
* 提交事务
* 回滚事务
* 3. Connection对象来管理事务
* 开启事务:setAutoCommit(boolean autoCommit) 参数为false:开启事务
* sql之前开启事务
* 提交事务:commit()
* sql都执行完提交事务
* 回滚事务:rollback()
* 在catch中回滚事务
*/
public class jdbcDemo8 {
public static void main(String[] args) {
new jdbcDemo8().login();
}
public boolean login(){
Connection conn = null;
PreparedStatement statement1 = null;
PreparedStatement statement2 = null;
try {
//连接数据库
conn = Utils.JDBCUtils.getconnection();
//开启事务
conn.setAutoCommit(false);
//定义SQL语句
String sql1 = "update account set balance = balance + ? where name = ?";
//获取sql1执行对象
statement1 = conn.prepareStatement(sql1);
//使用prepareStatement 子类的方法进行赋值
statement1.setInt(1,500);
statement1.setString(2,"zhangsan");
//执行SQL语句
statement1.execute();
String sql2 = "update account set balance = balance - ? where name =?";
//获取sql2的执行对象
statement2 = conn.prepareStatement(sql2);
statement2.setInt(1,500);
statement2.setString(2,"lisi");
statement2.execute();
//提交事务
conn.commit();
} catch (SQLException throwables) {
throwables.printStackTrace();
try {
conn.rollback();
} catch (SQLException e) {
e.printStackTrace();
}
}finally {
Utils.JDBCUtils.close(statement2,null);
Utils.JDBCUtils.close(statement1,conn);
}
return false;
}
}
使用jdbc执行SQL实现登录查询3 -事务查询版
最新推荐文章于 2022-06-12 10:39:31 发布