gpt4 book ai didi

mysql - 使用 node.js 将数据插入 mysql 工作,但脚本挂起

转载 作者:行者123 更新时间:2023-11-29 00:03:22 25 4
gpt4 key购买 nike

我有这个脚本用于读取文件,然后将数据插入到 mysql 表中。该脚本可以运行,但会挂起,因此我必须按 CTRL-C 来停止该脚本。但是脚本应该正常停止,我需要更改什么?

var fs = require('fs');
var filename;
var myGID;
filename = "data/insertUser1_next.json";

function get_line(filename, line_no, callback) {
fs.readFile(filename, function (err, data) {
if (err) throw err;

// Data is a buffer that we need to convert to a string
// Improvement: loop over the buffer and stop when the line is reached
var lines = data.toString('utf-8').split("\n");

if(+line_no > lines.length){
return callback('File end reached without finding line', null);
}

// lines
callback(null, lines[0], lines[1], lines[2], lines[3]);
});
}

get_line(filename, 0, function(err, line, line2, line3, line4){


line = line.replace(/(\r\n|\n|\r)/gm,"");
line2 = line2.replace(/(\r\n|\n|\r)/gm,"");
line3 = line3.replace(/(\r\n|\n|\r)/gm,"");
/*line4 = line4.replace(/(\r\n|\n|\r)/gm,"");*/
console.log('The line: ' + line);
console.log('The line2: ' + line2);
console.log('The line3: ' + line3);
console.log('The line4: ' + line4);

var post = {gid: line, uid: line2};
var post2 = {uid: line2, displayname: line3, password: line4};

var mysql = require('mysql');
var db_config = {
host : '123.456.789.012',
user : 'user',
password : 'password',
database : 'maindata'
};

var con = mysql.createPool(db_config);

con.getConnection(function(err){
if (err) {
console.log(err);
return;
}
con.query('INSERT INTO group_user SET ?', post, function(err, result) {
if (err) {
console.log(err);
return;
}

});
con.query('INSERT INTO users SET ?', post2, function(err, result) {
if (err) {
console.log(err);
return;
}

});
});
});

最佳答案

Here你可以看到发生了什么:

When you are done using the pool, you have to end all the connections or the Node.js event loop will stay active until the connections are closed by the MySQL server. This is typically done if the pool is used in a script or when trying to gracefully shutdown a server. To end all the connections in the pool, use the end method on the pool:

pool.end(function (err) {
// all connections in the pool have ended
});

因此,如果您在查询完成后放置 con.end(),脚本将正常终止

关于mysql - 使用 node.js 将数据插入 mysql 工作,但脚本挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28691251/

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