Node后台使用mysql并开启事务

如题;node后台使用mysql数据库,并使用事务来管理数据库操作。

这里主要讲一个事务的封装并写了一个INSERT 插入操作。

code:

基础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 }

相关操作步骤已经在注释中写明,本人实测有效。如需使用需加上自己的数据库配置及相关表明等动态配置。

有问题还原大家留言指正,国庆快到了祝大家节日快乐~

猜你喜欢

转载自www.cnblogs.com/leungUwah/p/9726978.html