Reputation: 55
I am developing a web app using nodejs and mysql. The mysql connection is working as fine but query is not excecuting and not showing any errors. My code ishown below. Pls help me.
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.
});
Upvotes: 0
Views: 3516
Reputation: 5872
If you try to print the err
in the connection it shows:
~/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
Clearly your database connection is getting closed before executing query. You need to move that close connection block into query block to force it's execution after query like this:
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.
});
});
}
});
When i ran it insertion was successful:
~/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)
Upvotes: 2