我已经 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/