mysql - Node MySQL 池连接中的事务处理

标签 mysql node.js

我已经 promise 了我的 mysql 连接,这样我就可以在我的 sql 连接中使用 promise 链。

var pool = mysql.createPool({
    connectionLimit: 50,
    host: keys.connection.host,
    multipleStatements: true,
    user: keys.connection.user,
    password: keys.connection.password,
    database: keys.connection.database,
    dateStrings: true 
    // debug:true                //Set this to true for verbose debugging. Leaving this to default for now cause it is creating too many messages at my console
})
pool.getConnection((err, connection) => {
    if (err) {
        if (err.code === 'PROTOCOL_CONNECTION_LOST') {
            console.error('Database connection was closed.')
        }
        if (err.code === 'ER_CON_COUNT_ERROR') {
            console.error('Database has too many connections.')
        }
        if (err.code === 'ECONNREFUSED') {
            console.error('Database connection was refused.')
        }
    }
    if (connection) connection.release()
    return
})

pool.query = util.promisify(pool.query)

我想在我的数据库中创建一些表,并且我不希望在其中一个查询失败时不执行任何查询

async function UpdateSchema_1_0_1() {
    try {

        await pool.query(`CREATE TABLE \`printer\`(
                        \`ID\` int(10) NOT NULL,
                        \`Station\` varchar(255) NOT NULL,
                        \`Printer\` varchar(255) NOT NULL,
                        \`XML\` varchar(6000) NOT NULL,
                        PRIMARY KEY (ID)
                    )`)

        await pool.query(`CREATE TABLE \`printerqueue\`(
            \`PrinterID\` int(10) NOT NULL,
            \`OrderNumber\` varchar(255) NOT NULL,
            FOREIGN KEY (PrinterID) REFERENCES printer(ID)
            );`)

        await pool.query(`Alter table users add column printerID int(10) Default 1;`)

        await pool.query(`ALTER TABLE users ADD CONSTRAINT fk_users_printer FOREIGN KEY (printerID) REFERENCES printer(ID);`)

    } catch (err) {
        console.log(err)
    }
}

有没有办法在我的 promisified mysql 池中使用提交和回滚事务?

最佳答案

无论如何都无法回滚 CREATE TABLE 或 ALTER TABLE 语句。这与连接池或 Node.js 无关。在 MySQL 中,每个 DDL(数据定义语言)语句都会导致隐式提交。

阅读https://dev.mysql.com/doc/refman/8.0/en/implicit-commit.html了解详情。

所以没有办法将一堆 DDL 语句作为一个原子组来执行(全部成功,否则回滚到目前为止所做的工作)。至少不使用原子事务的特性。

如果您的 DDL 语句之一失败,并且您希望“回滚”以将数据库返回到启动该组 DDL 语句之前的状态,那么您将必须手动撤消任何先前的 DDL 语句。

当然,某些类型的 DDL 更改无法撤消,除非从备份中恢复数据库,因为这些更改会破坏数据。像 DROP TABLE 或 ALTER TABLE... DROP COLUMN。要撤消这些更改并恢复该表或列中的数据,您必须拥有原始数据。

关于mysql - Node MySQL 池连接中的事务处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58148851/

相关文章:

mysql - 存储版本控制的数据库数据的标准/推荐方法是什么?

javascript - 在 V8 JavaScript (Chrome & Node.js) 中访问行号

javascript - ES6 中分号的使用

java - AES/CBC/PKCS5Padding Nodejs 加密

mysql - 什么决定是否为 SQL 列编写 MUL

mysql - MySQL 除法查询遇到问题(可能很简单修复)

mysql - 使用 AVG 函数计算多个数字的平均值

php循环mysql只执行一次

javascript - 优雅地在 Node 中插入对象字段

node.js - 如何返回响应然后在 nedb 中重定向?