当前位置: 首页 > news >正文

Node.js 数据库 事务 项目示例

1、参考:JavaScript语言的事务管理_js 函数 事务性-CSDN博客

或者百度搜索:Nodejs控制事务,

2、实践

2.1、对于MySQL或MariaDB,你可以使用mysqlmysql2库,并结合Promiseasync/await语法来控制事务。

使用 mysql2/promise 示例:
const mysql = require('mysql2/promise');async function runTransaction() {const connection = await mysql.createConnection({host: 'localhost',user: 'root',password: '123456',database: 'test',});try {await connection.beginTransaction();await connection.query('INSERT INTO users (name, email) VALUES (?, ?)',["heming","yyyyyy"]);await connection.query('INSERT INTO users (name, email) VALUES (?, ?)',["jackson","john2@example.com"]);await connection.commit();console.log('Transaction committed successfully.');} catch (error) {await connection.rollback();console.error('Transaction failed:', error);} finally {await connection.end();}
}runTransaction().catch(console.error);
当前表已有2条数据
第一次运行该文件时,第二个用户的email是john@example.com,违反了唯一约束,报错如下:

事务回滚,一条记录都没有插入成功。

然后把第二个用户的email改成john2@example.com,成功了,

表多了2条记录

2.2、使用Sequelize进行事务管理

以下是一个使用Sequelize在Node.js中管理事务的示例:

// 同步模型并创建用户 sequelize.sync().then(() => { createUser(); }); ```

在上面的示例中,我们创建了一个包含用户信息的简单数据库,并通过Sequelize的事务管理来确保两个用户记录的原子性。如果创建用户的过程中发生任何错误,事务将回滚,不会对数据库造成不一致的影响。

const { Sequelize, DataTypes } = require('sequelize'); 
const sequelize = new Sequelize('sqlite::memory:');const User = sequelize.define('User', { name: { type: DataTypes.STRING, allowNull: false } });async function createUser() { // 启动事务 const transaction = await sequelize.transaction();try {const user1 = await User.create({ name: 'Alice' }, { transaction });const user2 = await User.create({ name: 'Bob' }, { transaction });// 提交事务await transaction.commit();console.log("Users created:", user1, user2);} catch (error) {// 回滚事务await transaction.rollback();console.error("Error creating users:", error);}
}sequelize.sync().then(() => { createUser(); }); 

执行报错:

PS D:\soft\nodejs-crud-example> npm install sqlite3       
npm WARN deprecated glob@7.2.3: Glob versions prior to v9 are no longer supported
npm WARN deprecated gauge@4.0.4: This package is no longer supported.
npm WARN deprecated are-we-there-yet@3.0.1: This package is no longer supported.
npm WARN deprecated @npmcli/move-file@1.1.2: This functionality has been moved to @npmcli/fs
npm WARN deprecated inflight@1.0.6: This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful.
npm WARN deprecated npmlog@6.0.2: This package is no longer supported.
npm WARN deprecated rimraf@3.0.2: Rimraf versions prior to v4 are no longer supported
npm ERR! code 1
npm ERR! path D:\soft\nodejs-crud-example\node_modules\sqlite3
npm ERR! command failed
npm ERR! command C:\Windows\system32\cmd.exe /d /s /c prebuild-install -r napi || node-gyp rebuild
npm ERR! prebuild-install warn install read ECONNRESET
npm ERR! gyp info it worked if it ends with ok
npm ERR! gyp info using node-gyp@8.4.1
npm ERR! gyp info using node@20.10.0 | win32 | x64
npm ERR! gyp ERR! find Python
npm ERR! gyp ERR! find Python Python is not set from command line or npm configuration
npm ERR! gyp ERR! find Python Python is not set from environment variable PYTHON
npm ERR! gyp ERR! find Python checking if "python3" can be used
npm ERR! gyp ERR! find Python - "python3" is not in PATH or produced an error
npm ERR! gyp ERR! find Python checking if "python" can be used
npm ERR! gyp ERR! find Python - "python" is not in PATH or produced an error
npm ERR! gyp ERR! find Python checking if Python is C:\Users\Administrator\AppData\Local\Programs\Python\Python39\python.exe
npm ERR! gyp ERR! find Python - "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\python.exe" could not be run
npm ERR! gyp ERR! find Python checking if Python is C:\Program Files\Python39\python.exe
npm ERR! gyp ERR! find Python - "C:\Program Files\Python39\python.exe" could not be run
npm ERR! gyp ERR! find Python checking if Python is C:\Users\Administrator\AppData\Local\Programs\Python\Python39-32\python.exe
npm ERR! gyp ERR! find Python - "C:\Users\Administrator\AppData\Local\Programs\Python\Python39-32\python.exe" could not be run
npm ERR! gyp ERR! find Python checking if Python is C:\Program Files\Python39-32\python.exe
npm ERR! gyp ERR! find Python - "C:\Program Files\Python39-32\python.exe" could not be run
npm ERR! gyp ERR! find Python checking if Python is C:\Program Files (x86)\Python39-32\python.exe
npm ERR! gyp ERR! find Python - "C:\Program Files (x86)\Python39-32\python.exe" could not be run
npm ERR! gyp ERR! find Python checking if Python is C:\Users\Administrator\AppData\Local\Programs\Python\Python38\python.exe
npm ERR! gyp ERR! find Python - "C:\Users\Administrator\AppData\Local\Programs\Python\Python38\python.exe" could not be run
npm ERR! gyp ERR! find Python checking if Python is C:\Program Files\Python38\python.exe
npm ERR! gyp ERR! find Python - "C:\Program Files\Python38\python.exe" could not be run
npm ERR! gyp ERR! find Python checking if Python is C:\Users\Administrator\AppData\Local\Programs\Python\Python38-32\python.exe
npm ERR! gyp ERR! find Python - "C:\Users\Administrator\AppData\Local\Programs\Python\Python38-32\python.exe" could not be run
npm ERR! gyp ERR! find Python checking if Python is C:\Program Files\Python38-32\python.exe
npm ERR! gyp ERR! find Python - "C:\Program Files\Python38-32\python.exe" could not be run
npm ERR! gyp ERR! find Python checking if Python is C:\Program Files (x86)\Python38-32\python.exe
npm ERR! gyp ERR! find Python - "C:\Program Files (x86)\Python38-32\python.exe" could not be run
npm ERR! gyp ERR! find Python checking if Python is C:\Users\Administrator\AppData\Local\Programs\Python\Python37\python.exe
npm ERR! gyp ERR! find Python - "C:\Users\Administrator\AppData\Local\Programs\Python\Python37\python.exe" could not be run
npm ERR! gyp ERR! find Python checking if Python is C:\Program Files\Python37\python.exe
npm ERR! gyp ERR! find Python - "C:\Program Files\Python37\python.exe" could not be run
npm ERR! gyp ERR! find Python checking if Python is C:\Users\Administrator\AppData\Local\Programs\Python\Python37-32\python.exe
npm ERR! gyp ERR! find Python - "C:\Users\Administrator\AppData\Local\Programs\Python\Python37-32\python.exe" could not be run
npm ERR! gyp ERR! find Python checking if Python is C:\Program Files\Python37-32\python.exe
npm ERR! gyp ERR! find Python - "C:\Program Files\Python37-32\python.exe" could not be run
npm ERR! gyp ERR! find Python checking if Python is C:\Program Files (x86)\Python37-32\python.exe
npm ERR! gyp ERR! find Python - "C:\Program Files (x86)\Python37-32\python.exe" could not be run
npm ERR! gyp ERR! find Python checking if Python is C:\Users\Administrator\AppData\Local\Programs\Python\Python36\python.exe
npm ERR! gyp ERR! find Python - "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\python.exe" could not be run
npm ERR! gyp ERR! find Python checking if Python is C:\Program Files\Python36\python.exe
npm ERR! gyp ERR! find Python - "C:\Program Files\Python36\python.exe" could not be run
npm ERR! gyp ERR! find Python checking if Python is C:\Users\Administrator\AppData\Local\Programs\Python\Python36-32\python.exe
npm ERR! gyp ERR! find Python - "C:\Users\Administrator\AppData\Local\Programs\Python\Python36-32\python.exe" could not be run
npm ERR! gyp ERR! find Python checking if Python is C:\Program Files\Python36-32\python.exe
npm ERR! gyp ERR! find Python - "C:\Program Files\Python36-32\python.exe" could not be run
npm ERR! gyp ERR! find Python checking if Python is C:\Program Files (x86)\Python36-32\python.exe
npm ERR! gyp ERR! find Python - "C:\Program Files (x86)\Python36-32\python.exe" could not be run
npm ERR! gyp ERR! find Python checking if the py launcher can be used to find Python 3
npm ERR! gyp ERR! find Python - "py.exe" is not in PATH or produced an error
npm ERR! gyp ERR! find Python
npm ERR! gyp ERR! find Python **********************************************************
npm ERR! gyp ERR! find Python You need to install the latest version of Python.
npm ERR! gyp ERR! find Python Node-gyp should be able to find and use Python. If not,
npm ERR! gyp ERR! find Python you can try one of the following options:
npm ERR! gyp ERR! find Python - Use the switch --python="C:\Path\To\python.exe"
npm ERR! gyp ERR! find Python   (accepted by both node-gyp and npm)
npm ERR! gyp ERR! find Python - Set the environment variable PYTHON
npm ERR! gyp ERR! find Python - Set the npm configuration variable python:
npm ERR! gyp ERR! find Python   npm config set python "C:\Path\To\python.exe"
npm ERR! gyp ERR! find Python For more information consult the documentation at:
npm ERR! gyp ERR! find Python https://github.com/nodejs/node-gyp#installation
npm ERR! gyp ERR! find Python **********************************************************
npm ERR! gyp ERR! find Python
npm ERR! gyp ERR! configure error
npm ERR! gyp ERR! stack Error: Could not find any Python installation to use
npm ERR! gyp ERR! stack     at PythonFinder.fail (D:\soft\nodejs-crud-example\node_modules\node-gyp\lib\find-python.js:330:47)
npm ERR! gyp ERR! stack     at PythonFinder.runChecks (D:\soft\nodejs-crud-example\node_modules\node-gyp\lib\find-python.js:159:21)
npm ERR! gyp ERR! stack     at PythonFinder.<anonymous> (D:\soft\nodejs-crud-example\node_modules\node-gyp\lib\find-python.js:228:18)
npm ERR! gyp ERR! stack     at PythonFinder.execFileCallback (D:\soft\nodejs-crud-example\node_modules\node-gyp\lib\find-python.js:294:16)
npm ERR! gyp ERR! stack     at exithandler (node:child_process:430:5)
npm ERR! gyp ERR! stack     at ChildProcess.errorhandler (node:child_process:442:5)
npm ERR! gyp ERR! stack     at ChildProcess.emit (node:events:514:28)
npm ERR! gyp ERR! stack     at ChildProcess._handle.onexit (node:internal/child_process:292:12)
npm ERR! gyp ERR! stack     at onErrorNT (node:internal/child_process:484:16)
npm ERR! gyp ERR! stack     at process.processTicksAndRejections (node:internal/process/task_queues:82:21)
npm ERR! gyp ERR! System Windows_NT 10.0.19045
npm ERR! gyp ERR! command "C:\\Program Files\\nodejs\\node.exe" "D:\\soft\\nodejs-crud-example\\node_modules\\node-gyp\\bin\\node-gyp.js" "rebuild"
npm ERR! gyp ERR! cwd D:\soft\nodejs-crud-example\node_modules\sqlite3
npm ERR! gyp ERR! node -v v20.10.0
npm ERR! gyp ERR! node-gyp -v v8.4.1
npm ERR! gyp ERR! not oknpm ERR! A complete log of this run can be found in: C:\Users\Administrator\AppData\Local\npm-cache\_logs\2025-04-16T05_40_43_878Z-debug-0.log
PS D:\soft\nodejs-crud-example> 

相关文章:

  • 高版本Android (AIDL HAL) 使用HIDL方法
  • vue3 uniapp vite 配置之定义指令
  • 《vue3学习手记3》
  • 【UE5】连接射频线案例教程
  • 数据结构与算法[零基础]---4.树和二叉树
  • 视频孪生重构施工逻辑:智慧工地的数字化升级
  • JVM 内存调优
  • ctfshow——web入门191~194
  • 用户态网络缓冲区
  • 【课题推荐】多速率自适应卡尔曼滤波(MRAKF)用于目标跟踪
  • Hi3518E官方录像例程源码流程分析(三)
  • JVM:程序计数器、虚拟机栈、本地方法栈
  • Docker Compose 中配置 Host 网络模式
  • Spring Task(笔记)
  • Android --- FrameWork 入门:Product是什么?
  • winfrom 查询某字符串 找到它在 richTextbox 的位置 定位 并高亮 并且滚动定位到所查询的字符串所在的行
  • Meltdown原理介绍:用户空间读取内核内存
  • apt3.0和apt2.0的区别
  • AI数字人分身无限克隆,开启IP视频创作新纪元!
  • 如何判断一个js对象是否拥有某个属性(区分自身属性和原型链上的属性)?
  • 家在深圳房网论坛首页/搜索引擎优化工具
  • 网站开发工程师是什么意思/网络营销的推广手段
  • 网站建设还好做吗/seo外包公司
  • 还是网站好/参考网是合法网站吗?
  • 网站建设与管理单招/肇庆seo外包公司
  • 企业网站建设策划/搜狗搜索网页版