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

news2025/4/19 9:37:30

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 ok

npm 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> 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2336419.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Qt开发:QFileInfo详解

文章目录 一、QFileInfo 简介二、常用的构造函数三、常用函数的介绍和使用四、常用静态函数的介绍和使用五、完整代码示例 一、QFileInfo 简介 QFileInfo 提供了一个对象化的方式&#xff0c;用于访问文件系统中单个文件的信息。它可以接受&#xff1a; 文件名字符串&#xff…

蓝桥杯常考排序

1.逆序 Collections.reverseOrder() 方法对列表进行逆序排序。通过 Collections.sort() 方法配合 Collections.reverseOrder()&#xff0c;可以轻松实现从大到小的排序。 import java.util.ArrayList; // 导入 ArrayList 类&#xff0c;用于创建动态数组 import java.util.C…

深度学习基础:从入门到理解核心概念

引言 近年来&#xff0c;深度学习(Deep Learning)已成为人工智能领域最热门的研究方向之一。从AlphaGo战胜人类围棋冠军&#xff0c;到ChatGPT等大型语言模型的惊艳表现&#xff0c;深度学习技术正在深刻改变我们的生活和工作方式。本文将系统介绍深度学习的基础知识&#xff0…

科技项目验收测试报告有哪些作用?需要多长时间和费用?

在当今快速发展的科技环境中&#xff0c;科技项目的有效验收至关重要。对于公司、开发团队以及客户来说&#xff0c;科技项目验收测试报告更是一个不可缺少的一项重要环节。 科技项目验收测试报告是对一个项目在开发完成后所进行的一系列测试结果的总结。这份报告不仅用于证明…

CCLinkIE转ModbusTCP借网关之力打破组态王与三菱PLC通讯隔阂​

在某自动化生产线项目中&#xff0c;客户采用了三菱PLC作为现场控制核心&#xff0c;该PLC支持CCLinkIE现场总线协议。同时&#xff0c;客户希望使用组态王上位机软件进行生产过程的监控与管理&#xff0c;然而组态王上位机更擅长与ModbusTCP协议设备进行通讯。为了解决这一协议…

Linux网络编程第一课:深入浅出TCP/IP协议簇与网络寻址系统

知识点1【网络发展简史】 **网络节点&#xff1a;**路由器和交换机组成 交换机的作用&#xff1a;拓展网络接口 路由&#xff1a;网络通信路径 1、分组交换 分组的目的&#xff1a; 数据量大&#xff0c;不能一次型传输&#xff0c;只能分批次传输&#xff0c;这里的每一批…

GESP2023年12月认证C++七级( 第三部分编程题(2)纸牌游戏)

参考程序&#xff1a; #include <iostream> #include <cstring> // for memset #include <vector> using namespace std;const int max_n 1005; int n; int a[max_n], b[max_n], c[max_n]; // a[]: 得分系数&#xff1b;b[]: 换牌惩罚&#xff1b;c[]: …

HarmonyOS学习 实验九:@State和@Prop装饰器的使用方法

HarmonyOS应用开发&#xff1a;父子组件状态管理实验报告 引言 在HarmonyOS应用开发领域&#xff0c;组件之间的状态管理是一个至关重要的概念。通过有效的状态管理&#xff0c;我们可以确保应用的数据流动清晰、可预测&#xff0c;从而提升应用的稳定性和可维护性。本次实验…

【Ai】MCP实战:手写 client 和 server [Python版本]

什么是mcp MCP 是一个开放协议&#xff0c;它为应用程序向 LLM 提供上下文的方式进行了标准化。你可以将 MCP 想象成 AI 应用程序的 USB-C 接口。就像 USB-C 为设备连接各种外设和配件提供了标准化的方式一样&#xff0c;MCP 为 AI 模型连接各种数据源和工具提供了标准化的接口…

Java与C在典型场景下的性能对比深度剖析

&#x1f381;个人主页&#xff1a;User_芊芊君子 &#x1f389;欢迎大家点赞&#x1f44d;评论&#x1f4dd;收藏⭐文章 &#x1f50d;系列专栏&#xff1a;AI 【前言】 在计算机编程领域&#xff0c;Java和C语言都是举足轻重的编程语言。Java以其跨平台性、自动内存管理和丰富…

多智能体 AI 游戏框架(开源程序):竞争、发展、适应

一、软件介绍 文末提供程序和源码下载 SamoAI 在人类和 AI 之间创建了一个无缝的多代理叙事层&#xff0c;实现了跨多个平台的自然协作。通过一致的身份保留和情境记忆&#xff0c;它允许通过一系列行动随着时间的推移而演变的交互&#xff0c;就像人际关系一样。 二、核心概念…

java实现二叉树的前序、中序、后序遍历(递归和非递归方式)以及层级遍历

java实现二叉树的前序、中序、后序遍历以及层级遍历 一、二叉树节点定义二、递归方式1.前序遍历2.中序遍历3.后序遍历 三、非递归方式1.前序遍历2.中序遍历3.后序遍历4.层级遍历5.分层打印 四、测试用例 一、二叉树节点定义 class TreeNode {int val;TreeNode left;TreeNode r…

Solr admin 更新文档

<add><doc><field name"id">1904451090351546368</field><field name"companyName" update"set">测试科技有限公司</field></doc> </add>

【Netty篇】EventLoopGroup 与 EventLoop 详解

目录 开场白&#xff1a;话说 Netty 江湖第一段&#xff1a;EventLoopGroup——“包工头”的角色第二段&#xff1a;EventLoop——“身怀绝技的工人”第三段&#xff1a;EventLoop 如何处理 I/O 事件、普通任务和定时任务第四段&#xff1a;Handler 执行中如何换人&#xff1f;…

操作系统之shell实现(上)

&#x1f31f; 各位看官好&#xff0c;我是maomi_9526&#xff01; &#x1f30d; 种一棵树最好是十年前&#xff0c;其次是现在&#xff01; &#x1f680; 今天来学习C语言的相关知识。 &#x1f44d; 如果觉得这篇文章有帮助&#xff0c;欢迎您一键三连&#xff0c;分享给更…

数据结构与算法——链表OJ题详解(2)

文章目录 一、前言二、OJ续享2.1相交链表2.2环形链表12.2环形链表2 三、总结 一、前言 哦了兄弟们&#xff0c;咱们上次在详解链表OJ题的时候&#xff0c;有一部分OJ题呢up并没有整理完&#xff0c;这一个星期呢&#xff0c;up也是在不断的学习并且沉淀着&#xff0c;也是终于…

Linux 基础知识详解

Linux 基础知识详解 一、快照与克隆 1. &#x1f4f8;快照&#xff08;Snapshot&#xff09; 快照是虚拟机当前运行状态的一次“瞬间拷贝”&#xff0c;包括内存、磁盘、配置等信息。这使得管理员能够快速恢复到某个特定的时间点。 用途&#xff1a; 安全实验前保存状态&am…

centOs7配置有限网络

最简单快速的是使用nmtui命令&#xff0c;采用图形页面修改。 点击编辑连接并回车&#xff1a; 选中编辑然后回车&#xff1a; 千万记住DNS服务器就是子网掩码&#xff0c;不是常说的DNS域名。把地址&#xff0c;网关&#xff0c;子网掩码配置好。只要ip不冲突&#xff0c;网…

C语言 —— 指尖跃迁 刻印永恒 - 文件操作

目录 1. 什么是文件 1.1 程序文件 1.2 数据文件 1.3 文件名 2. 二进制文件和文本文件 3. 文件的打开与关闭 3.1 流和标准流 3.2 文件指针 3.3 文件的打开与关闭 fopen fclose 4. 文件的顺序读写 4.1 fgetc和fputc fgetc fputc 4.2 fgets和fputs fgets fputs…

网络安全与信息安全的区别​及共通

在数字化时代&#xff0c;网络安全与信息安全已成为保障个人、企业乃至国家正常运转的重要防线。尽管二者紧密相关且常被混为一谈&#xff0c;但实则存在显著差异。当然&#xff0c;它们也有一些相同点&#xff0c;比如都以保障数字环境下的安全为核心目标&#xff0c;均需要通…