Node.js 是一种 JavaScript 运行时环境,可以让你在服务端使用 JavaScript 编写代码。MySQL2 是一个用于连接和操作 MySQL 数据库的 Node.js 模块。
事务是数据库管理系统中用来维护数据一致性的机制。在事务中的所有操作要么全部成功,要么全部失败。这意味着,如果在事务中的某个操作失败了,则可以将数据库回滚到事务开始之前的状态。
在 MySQL2 中,你可以使用
connection.beginTransaction()
方法来开始一个事务,使用
connection.commit()
方法提交事务,使用
connection.rollback()
方法回滚事务。例如:
const mysql = require('mysql2/promise');
async function updateInventory(itemId, quantity) {
const connection = await mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'test'
try {
await connection.beginTransaction();
const [rows, fields] = await connection.query(
'SELECT quantity FROM inventory WHERE item_id = ?',
[itemId]
const oldQuantity = rows[0].quantity;
const newQuantity = oldQuantity - quantity;
await connection.query(
'UPDATE inventory SET quantity = ? WHERE item_id = ?',
[newQuantity, itemId]
await connection.commit();
} catch (error) {
await connection.rollback();
throw error;
} finally {
connection.end();
在上面的代码中,我们开始一个事务,然后从 inventory
表中获取某个物品的库存数量,再将库存数量减去一个指定的数量,最后提交事务。如果在执行查询或更新时发