第四周02
今天学习了在 Java Web 开发中的事务处理。事务是一组数据库操作,这些操作要么全部成功执行,要么全部不执行,以保证数据的一致性和完整性。在 JDBC 中,可以通过Connection对象来管理事务。
假设有两个数据库表accounts和transactions,进行一个转账操作,涉及到两个表的更新,需要将其放在一个事务中:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class TransactionExample {
public static void transferMoney(double amount, int fromAccountId, int toAccountId) {
Connection connection = null;
PreparedStatement fromStatement = null;
PreparedStatement toStatement = null;
try {
connection = DBUtil.getConnection();
connection.setAutoCommit(false);
String fromSql = "UPDATE accounts SET balance = balance -? WHERE id =?";
fromStatement = connection.prepareStatement(fromSql);
fromStatement.setDouble(1, amount);
fromStatement.setInt(2, fromAccountId);
int rowsAffected1 = fromStatement.executeUpdate();
String toSql = "UPDATE accounts SET balance = balance +? WHERE id =?";
toStatement = connection.prepareStatement(toSql);
toStatement.setDouble(1, amount);
toStatement.setInt(2, toAccountId);
int rowsAffected2 = toStatement.executeUpdate();
if (rowsAffected1 > 0 && rowsAffected2 > 0) {
connection.commit();
System.out.println("Transfer successful.");
} else {
connection.rollback();
System.out.println("Transfer failed.");
}
} catch (SQLException e) {
if (connection != null) {
try {
connection.rollback();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
e.printStackTrace();
} finally {
try {
if (fromStatement != null) fromStatement.close();
if (toStatement != null) toStatement.close();
if (connection != null) connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
在这个例子中,通过connection.setAutoCommit(false)关闭自动提交,然后执行两个更新操作,如果两个操作都成功则调用connection.commit()提交事务,否则调用 connection rollback()回滚事务。这样可以确保在转账过程中,即使其中一个更新操作失败,整个转账操作也不会对数据库造成不一致的影响。
在实际的 Java Web 项目中,事务处理通常会结合业务逻辑进行封装。例如,在一个电商系统中,订单创建涉及到库存扣减、订单表插入等多个数据库操作,这些操作必须在一个事务中完成,以保证数据的一致性。通过合理运用事务,能有效避免因部分操作失败导致的数据错误,提升系统的可靠性。
浙公网安备 33010602011771号