大致的实现思路(SQL语句不支持try-catch):
try {
set autocommit =0; //在事务结束之前的所有DML处于同一个事务中。
update account set money=money-100 where card_id='1234567890';
update account set money=moy-100 where card_id='0515151515'
commit; //提交事务,将DML语句执行结果持久化到磁盘。
}catch() {
rollback;
}
java代码完善:
package jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class Text {
public static void main(String[] args) {
Connection connection = null;
Statement statement=null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test", "root","root");//2,建立连接
connection.setAutoCommit(false);
statement= connection.createStatement();
statement.addBatch("update account set money=money-100 where card_id= '1234567890'");
statement.addBatch("update account set money=money+100 where card_id= '0987654321'");
statement.executeBatch();
connection.commit();
} catch (Exception e) {
try {
if (connection!=null) {
connection.rollback();
}
} catch (SQLException e1) {
e1.printStackTrace();
}
}finally {
try {
if (statement!=null) {
statement.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (connection!=null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
此时执行结果
思考:如果此时sql语句部分出错
package jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class Text {
public static void main(String[] args) {
Connection connection = null;
Statement statement=null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test", "root","root");//2,建立连接
connection.setAutoCommit(false);
statement= connection.createStatement();
statement.addBatch("update account set money=money-100 where card_id= '1234567890'");
statement.addBatch("update account set mon=money+100 where card_id= '0987654321'");//出错的部分
statement.executeBatch();
connection.commit();
} catch (Exception e) {
try {
if (connection!=null) {
connection.rollback();
}
} catch (SQLException e1) {
e1.printStackTrace();
}
}finally {
try {
if (statement!=null) {
statement.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (connection!=null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
控制台输出结果:
数据库输出结果
分析:由于其中一条SQL语句出错,则会被catch语句捕捉,输出对应异常信息,事务执行回滚,导致SQL语句对应的操作,上述输出结果则印证了这一点。