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.pswp.cn/news/901992.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/901992.shtml
英文地址,請注明出處:http://en.pswp.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…