Node後臺使用mysql並開啓事務

如題;node後臺使用mysql數據庫,並使用事務來管理數據庫操做。node

這裏主要講一個事務的封裝並寫了一個INSERT 插入操做。mysql

code:sql

基礎code:

db.config.js
 1 const mysql = require('mysql')
 2 
 3 const pool = mysql.createPool({
 4   connectionLimit: 20, //鏈接池鏈接數
 5   host: 'localhost', //數據庫地址,這裏用的是本地
 6   database: 'xxxx', //數據庫名稱
 7   user: 'xxxxx',  // username
 8   password: '*****' // password
 9 })
10 //返回一個Promise連接
11 const connectHandle = () => new Promise((resolve, reject) => {
12   pool.getConnection((err, connection) => {
13     if(err) {
14       console.error('連接錯誤:' + err.stack + '\n' + '連接ID:' + connection.threadId)
15       reject(err)
16     } else {
17       resolve(connection)
18     }
19   })
20 })
21 
22 
23 
24 module.exports = connectHandle

事務操做

 1 const connectHandler = require('./db.config') //引入上面所講的數據庫基礎配置
 2 
 3 const insertHandler = async (vals) => {
 4   const connection = await connectHandler() // 獲得連接
 5   const tablename = 'xxxxx' //動態table(表)名稱
 6   //開啓事務
 7   connection.beginTransaction( err => {
 8     if(err) {
 9       return '開啓事務失敗'
10     } else {
11        //執行INSERT插入操做
12       connection.query(`INSERT INTO ${tablename} SET ?`, vals, (e, rows, fields) => {
13         if(e) {
14           return connection.rollback(() => {
15             console.log('插入失敗數據回滾')
16           })
17         } else {
18           connection.commit((error) => {
19             if(error) {
20               console.log('事務提交失敗')
21             }
22           })
23           connection.release()  // 釋放連接
24           return {rows, success: true}  // 返回數據庫操做結果這裏數據格式可根據我的或團隊規範來定製
25         }
26       })
27     }
28   })
29 }
30 
31 
32 module.exports = {
33   insertHandler
34 }

相關操做步驟已經在註釋中寫明,本人實測有效。如需使用需加上本身的數據庫配置及相關代表等動態配置。數據庫

有問題還原你們留言指正,國慶快到了祝你們節日快樂~async

相關文章
相關標籤/搜索