gpt4 book ai didi

mysql - 调用退出后无法排队查询

转载 作者:行者123 更新时间:2023-11-30 21:58:12 24 4
gpt4 key购买 nike

根据 Node MySQL 文档 (https://github.com/mysqljs/mysql#introduction):

您在连接上调用的每个方法都会排队并按顺序执行。

关闭连接是使用 end() 完成的,它确保在向 mysql 服务器发送退出数据包之前执行所有剩余的查询。

然而,下面的代码不起作用,因为 connection.end() 方法在 SQL 查询运行之前被调用。如果我注释掉 connection.end() 行,它可以工作,但是脚本在完成时挂起(不关闭/结束),需要我按 ctrl-c 来结束它。

如果我将 MySQL connection 对象和 connection.end() 调用移动到 lineReader.createInterface().on() block ,它有效 - 脚本在最后正确终止......但它正在为每个 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();

最佳答案

您可以在 close 事件监听器中调用 connection.end():

lineReader.createInterface({
input: file.createReadStream('proxies/proxies.txt')
}).on('line', function (line) {
...
}).on('close', function() {
connection.end();
});

关于mysql - 调用退出后无法排队查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44345463/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com