Mein Nodejs-Projekt verwendet derzeit node-mysql.Nodejs - Knoten-Mysql-Transaktion mit einer Schleife
Ich habe ein mehrstufiges Datenarray, das ich in mehrere Tabellen einfügen möchte. Transaktion ist das, woran ich gedacht habe, um mein Ziel zu erreichen. Im Folgenden finden Sie die Umrisse meines Codes:
const mysql = require("mysql")
const pool = mysql.createPool({ // connectionLimit=10 by default
connectionLimit: 5, // 10 by default
host: 'somehost',
user: 'userblah',
password: 'passworblah',
database: 'dbblah'
})
pool.getConnection(function(err, dbConnection) {
dbConnection.beginTransaction(function(err1) {
if (err1) {
console.log(“Unable to begin the transaction”)
return
}
arrayElements.forEach(function(element) {
var insert1 = mysql.format(“INSERT INTO table1(…) VALUES (…)”, […])
dbConnection.query(insert1, function(error1, result1) {
if (error1) {
return dbConnection.rollback(function() {
console.log(“Insert failed”)
})
}
const lastID = result1.insertId
// A: more loops coming here to insert sub-data to more tables with lastID
// B: SHOULD I dbConnection.commit here???
})
})
}
}
Ich denke, es ist an B
-dbConnection.commit
zu früh ist (während die forEach
los ist)? Was soll ich tun, um sicherzustellen, dass alles erledigt ist, dann commit
?
Danke, 'async' deutet darauf hin! – quanguyen