最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Node MySQL池连接中的事务处理

运维笔记admin9浏览0评论

Node MySQL池连接中的事务处理

Node MySQL池连接中的事务处理

我已承诺了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)
    }
}

有没有一种方法可以在我承诺的mysql池中使用提交和回滚事务?

回答如下:

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

阅读https://dev.mysql/doc/refman/8.0/en/implicit-commit.html以获取详细信息。

因此,无法将一堆DDL语句作为一个原子组进行处理(全部成功或回滚到目前为止已完成的工作)。至少没有使用原子事务的功能。

如果您的DDL语句之一失败,并且您想“回滚”以将数据库恢复为开始启动DDL语句组之前的状态,那么您将必须手动撤消所有先前的DDL语句。 >

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

发布评论

评论列表(0)

  1. 暂无评论