根据Node MySQL文档(https://github.com/mysqljs/mysql#introduction):
Every method you invoke on a connection is queued and executed in sequence.
和
Closing the connection is done using end() which makes sure all remaining queries are executed before sending a quit packet to the mysql server.
然而,下面的代码不起作用,因为在SQL查询可以运行之前调用connection.end()
方法。如果我注释掉connection.end()
行,它会起作用,但是脚本在完成时会挂起(不会关闭/结束),要求我按ctrl-c结束它。
如果我将MySQL connection
对象和connection.end()
调用移动到lineReader.createInterface().on()
块,它可以正常工作 - 脚本正确终止...但它正在创建一个新连接对于每个INSERT
语句。
每次关闭和重新连接似乎都是正确的。我误解了Node MySQL文档吗?还有更好的方法吗?
let lineReader = require('readline');
let file = require('fs');
let mysql = require('mysql');
let connection = mysql.createConnection({
host: '127.0.0.1',
port: 33060,
user: 'homestead',
password: 'secret',
database: 'sentinel',
});
lineReader.createInterface({
input: file.createReadStream('proxies/proxies.txt')
}).on('line', function (line) {
let ary = line.split(/[:, ]/);
let insert_sql;
if (typeof ary[2] !== 'undefined' && typeof ary[3] !== 'undefined') {
insert_sql =
'INSERT INTO proxies (host, port, username, password) ' +
'VALUES ("' + ary[0] + '", "' + ary[1] + '", "' + ary[2] + '", "' + ary[3] + '")';
} else {
insert_sql =
'INSERT INTO proxies (host, port) ' +
'VALUES ("' + ary[0] + '", "' + ary[1] + '")';
}
connection.query(insert_sql, function (error, results, fields) {
if (error) {
console.log('error: ' + error);
} else {
console.log('success: ' + insert_sql);
}
});
});
connection.end();
答案 0 :(得分:0)
您可以在connection.end()
事件监听器中调用close
:
lineReader.createInterface({
input: file.createReadStream('proxies/proxies.txt')
}).on('line', function (line) {
...
}).on('close', function() {
connection.end();
});