事务的传播机制 代码示例
时间: 2023-08-23 11:06:48 浏览: 34
以下是一个简单的事务传播机制的代码示例,使用Java语言和JDBC连接数据库:
```java
import java.sql.*;
public class TransactionExample {
public void transferMoney(String fromAccount, String toAccount, double amount) {
Connection conn = null;
PreparedStatement stmt1 = null;
PreparedStatement stmt2 = null;
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "username", "password");
conn.setAutoCommit(false); // 开启事务
// 扣除转出账户的金额
stmt1 = conn.prepareStatement("UPDATE accounts SET balance = balance - ? WHERE account_number = ?");
stmt1.setDouble(1, amount);
stmt1.setString(2, fromAccount);
stmt1.executeUpdate();
// 增加转入账户的金额
stmt2 = conn.prepareStatement("UPDATE accounts SET balance = balance + ? WHERE account_number = ?");
stmt2.setDouble(1, amount);
stmt2.setString(2, toAccount);
stmt2.executeUpdate();
conn.commit(); // 提交事务
System.out.println("Money transferred successfully.");
} catch (SQLException e) {
try {
conn.rollback(); // 回滚事务
} catch (SQLException ex) {
ex.printStackTrace();
}
e.printStackTrace();
} finally {
try {
if (stmt1 != null) {
stmt1.close();
}
if (stmt2 != null) {
stmt2.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
```
在上面的代码示例中,`transferMoney`方法通过JDBC连接到数据库,并在开启事务后执行两个UPDATE语句来转移一定金额的资金。如果任何一个UPDATE语句失败,就会回滚整个事务。最后,无论事务成功还是失败,都会关闭所有连接和语句。