我正在使用nodejs和mysql开发一个Web应用程序。 mysql连接正常工作,但查询不是正常,并没有显示任何错误。我的代码如下所示。请帮助我。
var mysql = require("mysql");
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database : "db"
});
con.connect(function(err){
if(err){
console.log('Error connecting to Db');
return;
} else {
var time = Date.now();
var post = {userphone: "user", senderphone: "to1", message: "msg", time:time};
var query = con.query('INSERT INTO chat SET ?', post, function(err, result) {
console.log('db added');
console.log(query.sql);
});
console.log('Connection established');
}
});
con.end(function(err) {
// The connection is terminated gracefully
// Ensures all previously enqueued queries are still
// before sending a COM_QUIT packet to the MySQL server.
});
答案 0 :(得分:2)
如果您尝试在显示的连接中打印err
:
~/Documents/src : $ node testInsert.js
Connection established
{ [Error: Cannot enqueue Query after invoking quit.] code: 'PROTOCOL_ENQUEUE_AFTER_QUIT', fatal: false }
db added
INSERT INTO chat SET `userphone` = 'user', `senderphone` = 'to1', `message` = 'msg', `time` = 1493132496360
显然,在执行查询之前,您的数据库连接已关闭。您需要将该关闭连接块移动到查询块中以强制它在查询之后执行,如下所示:
con.connect(function(err){
console.log('Connection established');
if(err){
console.log('Error connecting to Db');
return;
} else {
var time = Date.now();
var post = {userphone: "user", senderphone: "to1", message: "msg", time:time};
var query = con.query('INSERT INTO chat SET ?', post, function(err, result) {
if(err) console.log(err);
console.log('db added');
console.log(query.sql);
con.end(function(err) {
// The connection is terminated gracefully
// Ensures all previously enqueued queries are still
// before sending a COM_QUIT packet to the MySQL server.
});
});
}
});
当我运行它时,插入成功:
~/Documents/src : $ node testInsert.js
Connection established
db added
INSERT INTO chat SET `userphone` = 'user', `senderphone` = 'to1', `message` = 'msg', `time` = 1493132632444
mysql> SELECT * FROM chat;
+-----------+-------------+---------------------+---------+
| userphone | senderphone | time | message |
+-----------+-------------+---------------------+---------+
| user | to1 | 0000-00-00 00:00:00 | msg |
+-----------+-------------+---------------------+---------+
1 row in set (0.00 sec)