gpt4 book ai didi

mysql - NodeJS mysql 没有插入到表中

转载 作者:行者123 更新时间:2023-11-29 07:37:32 25 4
gpt4 key购买 nike

我有一个数据库,其中包含一个名为 responses 的表,描述为

 +----------+----------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------+----------+------+-----+---------+-------+
| user | char(25) | YES | | NULL | |
| response | text | YES | | NULL | |
+----------+----------+------+-----+---------+-------+

当我像这样插入数据库时​​:

connection.connect(function(err) {
if (err) {
console.error('error connecting: ' + err.stack);
return;
}
console.log('connected as id ' + connection.threadId);
var sql = "INSERT INTO responses (user, response) VALUES ('test_user', 'A')";
connection.query(sql, function (err, result) {
if (err) throw err;
console.log("1 record inserted");
connection.end();
});
});

它抛出一个错误,提示错误:调用退出后无法排队查询。

我在应用程序中连接到数据库正常,但由于某种原因这个查询不起作用,有什么建议吗?

最佳答案

您不需要连接函数,因为如果未连接,调用查询将为您调用连接。

将连接端放在函数之外。

另请注意,在 NodeJs 中,您通常仅在应用关闭时关闭连接。它提高了性能,因为不需要重新连接每个新查询

 var sql = "INSERT INTO responses (user, response) VALUES ('test_user', 'A')";
connection.query(sql, function (err, result) {
if (err) throw err;
console.log("1 record inserted");

});
connection.end();

关于mysql - NodeJS mysql 没有插入到表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48026738/

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