Reputation: 5800
The below NodeJS app is running perfectly fine without process.exit() when I add process.exit() it closes the window after executing (which I what I am after) but it's not executing the SQL query.
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)
The above code doesn't insert into MySQL
If I remove process.exit(0) it inserts into MySQL
Upvotes: 2
Views: 314
Reputation: 2907
try this:
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
})
});
Upvotes: 2
Reputation: 707326
You need to not call process.exit()
until your query has completed by moving the call inside the completion callback for the query. You also need some work on your error handling so you log errors and cleanup properly when there's an error:
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);
});
});
Upvotes: 2