下面的NodeJS应用程序在没有process.exit()的情况下运行得非常好,当我添加process.exit()时,它在执行后关闭窗口(这是我想要的),但它不执行SQL查询。
var mysql = require('mysql')
var conn = mysql.createPool({
connectionLimit : 10000,
host: "localhost",
user: "root",
password: "password",
database: "mydatabase",
port: 3306
});
var values = ""
for (var i=0; i < 300; i++) {
var pub = //some randomvalue
var hub = //some randomvalue
values += "('"+pub + "', '" + hub + "'), "
console.log(i);
}
var valuesx = values.slice(0, -2)
var sql = "INSERT INTO `test` (pub, hub) VALUES "
var sqlx = sql + valuesx;
conn.getConnection(function(err, con) {
if (err) throw err
con.query(sqlx)
con.release();
});
process.exit(0)
上面代码不会插入到MySQL中
如果删除process.exit(0),它将插入MySQL
试试看:
conn.getConnection(function(err, con) {
if (err) throw err
con.query(sqlx, function (err2, result) {
if (err2) throw err;
con.release();
process.exit(0)
// you should put these inside this callback
})
});
在查询完成之前,您不需要调用process.exit()
,方法是将调用移动到查询的完成回调中。您还需要在错误处理方面做一些工作,以便记录错误并在出现错误时正确清除:
conn.getConnection(function(err, con) {
// need real error handling here too as just a throw err won't do anything useful
if (err) {
console.log(err);
process.exit(1);
}
con.query(sqlx, function(err, data) {
let exitCode = 0;
if (err) {
console.log(err);
exitCode = 2;
}
con.release();
process.exit(exitCode);
});
});