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> 

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

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

相关文章

【Mamba】MambaVision论文阅读

文章目录 MambaVision一、研究背景&#xff08;一&#xff09;Transformer vs Mamba​&#xff08;二&#xff09;Mamba in CV​ 二、相关工作​&#xff08;一&#xff09;Transformer 在计算机视觉领域的进展​&#xff08;二&#xff09;Mamba 在计算机视觉领域的探索​ 三、…

前端面试宝典---原型链

引言----感谢大佬的讲解 大佬链接 原型链示意图 原型链问题中需要记住一句话&#xff1a;一切变量和函数都可以并且只能通过__proto__去找它所在原型链上的属性与方法 原型链需要注意的点 看上图可以发现 函数&#xff08;构造函数&#xff09;也可以通过__proto__去找到原…

C语言---FILE结构体

一、FILE 结构体的本质与定义 基本概念 FILE 是 C 语言标准库中用于封装文件操作的结构体类型&#xff0c;定义于 <stdio.h> 中。它代表一个“文件流”&#xff0c;可以是磁盘文件、标准输入输出&#xff08;stdin/stdout/stderr&#xff09;或其他输入输出设备。 实现特…

基于大模型的直肠息肉诊疗全流程风险预测与方案优化研究报告

目录 一、引言 1.1 研究背景与意义 1.2 研究目的与创新点 二、大模型技术概述 2.1 大模型原理简介 2.2 大模型在医疗领域应用现状 三、直肠息肉术前预测与准备 3.1 基于大模型的术前风险预测 3.1.1 息肉性质预测 3.1.2 手术难度预测 3.2 基于预测结果的术前准备 3.…

华为OD机试真题——MELON的难题(2025A卷:200分)Java/python/JavaScript/C++/C语言/GO六种最佳实现

2025 A卷 200分 题型 本文涵盖详细的问题分析、解题思路、代码实现、代码详解、测试用例以及综合分析&#xff1b; 并提供Java、python、JavaScript、C、C语言、GO六种语言的最佳实现方式&#xff01; 2025华为OD真题目录全流程解析/备考攻略/经验分享 华为OD机试真题《MELON的…

AI数据分析与BI可视化结合:解锁企业决策新境界

大家好&#xff0c;今天我们来聊聊一个前沿而热门的话题——AI数据分析与BI可视化结合&#xff0c;如何携手推动企业决策迈向新高度。在数据爆炸的时代&#xff0c;企业如何高效利用这些数据&#xff0c;成为制胜的关键。AI数据分析与BI可视化的结合&#xff0c;正是解锁这一潜…

克服储能领域的数据处理瓶颈及AI拓展

对于储能研究人员来说&#xff0c;日常工作中经常围绕着一项核心但有时令人沮丧的任务&#xff1a;处理实验数据。从电池循环仪的嗡嗡声到包含电压和电流读数的大量电子表格&#xff0c;研究人员的大量时间都花在了提取有意义的见解上。长期以来&#xff0c;该领域一直受到对专…

【SpringBoot+Vue自学笔记】002 SpringBoot快速上手

跟着这位老师学习的&#xff1a;https://www.bilibili.com/video/BV1nV4y1s7ZN?vd_sourceaf46ae3e8740f44ad87ced5536fc1a45 最好和老师的idea版本完全一致&#xff01;截至本文写的当日最新的idea好像默认jdk17&#xff0c;配置时遇到很多bug。 &#x1f33f; Spring Boot&a…

SpringAI+DeepSeek大模型应用开发——2 大模型应用开发架构

目录 2.大模型开发 2.1 模型部署 2.1.1 云服务-开放大模型API 2.1.2 本地部署 搜索模型 运行大模型 2.2 调用大模型 接口说明 提示词角色 ​编辑 会话记忆问题 2.3 大模型应用开发架构 2.3.1 技术架构 纯Prompt模式 FunctionCalling RAG检索增强 Fine-tuning …

蓝桥杯12. 日期问题

日期问题 原题目链接 题目描述 小明正在整理一批历史文献。这些历史文献中出现了很多日期。 小明知道这些日期都在 1960 年 1 月 1 日 至 2059 年 12 月 31 日 之间。 令小明头疼的是&#xff0c;这些日期采用的格式非常不统一&#xff1a; 有的采用 年/月/日有的采用 月…

STM32使用rand()生成随机数并显示波形

一、随机数生成 1、加入头文件&#xff1a;#include "stdlib.h" 2、定义一个用作生成随机数种子的变量并加入到滴答定时器中不断自增&#xff1a;uint32_t run_times 0; 3、设置种子&#xff1a;srand(run_times);//每次生成随机数前调用一次为佳 4、生成一个随…

『前端样式分享』联系我们卡片式布局 自适应屏幕 hover动效 在wikijs中使用 (代码拿来即用)

目录 预览效果分析要点响应式网格布局卡片样式&#xff1a;阴影和过渡效果 代码优化希望 长短不一的邮箱地址在左右居中的同时,做到左侧文字对齐(wikijs可用)总结 欢迎关注 『前端布局样式』 专栏&#xff0c;持续更新中 欢迎关注 『前端布局样式』 专栏&#xff0c;持续更新中…

【ubuntu】在Linux Yocto的基础上去适配Ubuntu的wifi模块

一、修改wifi的节点名 1.找到wifi模块的PID和VID ifconfig查看wifi模块网络节点的名字&#xff0c;发现是wlx44876393bb3a&#xff08;wlxmac地址&#xff09; 通过udevadm info -a /sys/class/net/wlx44876393bba路径的命令去查看wlx44876393bba的总线号&#xff0c;端口号…

健康养生:开启活力生活新篇章

在当代社会&#xff0c;熬夜加班、久坐不动、外卖快餐成为许多人的生活常态&#xff0c;随之而来的是各种亚健康问题。想要摆脱身体的疲惫与不适&#xff0c;健康养生迫在眉睫&#xff0c;它是重获活力、拥抱美好生活的关键。​ 应对不良饮食习惯带来的健康隐患&#xff0c;饮…

【verilog】多个 if 控制同一个变量(后面会覆盖前面)非阻塞赋值真的并行吗?

非阻塞赋值 (<) 是“并行”的&#xff0c;但是代码顺序会影响结果&#xff1f;”这正是 Verilog 的硬件描述本质 vs 行为语义之间的微妙之处。 &#x1f4a1;1. 非阻塞赋值真的并行吗&#xff1f; 是的&#xff01;非阻塞赋值 < 从行为上是并行的&#xff0c;也就是说&a…

前沿篇|CAN XL 与 TSN 深度解读

引言 1. CAN XL 标准演进与设计目标 2. CAN XL 物理层与帧格式详解 3. 时间敏感网络 (TSN) 关键技术解析 4. CAN XL + TSN 在自动驾驶领域的典型应用

vscode、cherry studio接入高德mcp服务

最近mcp协议比较火&#xff0c;好多平台都已经开通了mcp协议&#xff0c;今天来接入下高德的mcp看看效果如何。 话不多说&#xff0c;咱们直接开干。 先来看下支持mcp协议的工具有cusor、cline等等。更新cherrystudio后发现上面也有mcp服务器了。今天咱就来试试添加高德的mcp协…

Triton(2)——Triton源码接结构

1 triton 3.0.0 源码结构 triton docs/&#xff1a;项目文档 cmake/&#xff1a;构建配置相关 bin/&#xff1a;工具、脚本 CmakeLists.txt&#xff1a;cmake 配置文件 LSCENSE README.md Pyproject.toml&#xff1a;python 项目配置文件 utils/&#xff1a;项目配置文…

React 事件处理基础

React 中最常见的两个需求&#xff0c;一个是列表渲染&#xff0c;另一个就是绑定点击事件。 这一篇就是从最基础的按钮点击开始&#xff0c;分四个阶段&#xff0c;逐步理解 React 中事件的写法和参数传递方式。 &#x1f4cd;阶段一&#xff1a;最简单的点击事件 function A…

java的lambda和stream流操作

Lambda 表达式 ≈ 匿名函数 &#xff08;Lambda接口&#xff09;函数式接口&#xff1a;传入Lambda表达作为函数式接口的参数 函数式接口 只能有一个抽象方法的接口 Lambda 表达式必须赋值给一个函数式接口&#xff0c;比如 Java 8 自带的&#xff1a; 接口名 作用 Functio…