1

I have a database with a table called responses described as

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

When I am inserting into the database such as this:

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();
 });
 });

It is throwing an error saying Error: Cannot enqueue Query after invoking quit.

I connect to the DB fine in the application, but for some reason this query doesn't work, any suggestions?

2
  • can you try only doing this part without the connect part 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(); }); Commented Dec 29, 2017 at 19:59
  • Do you mean outside of the function? @Amit Commented Dec 29, 2017 at 21:48

1 Answer 1

1

you don`t need the connect function as calling query will call connect for you if not connected.

put the connection end outside of the function.

also note the in NodeJs you usually close the connection only when you app closes. its increase the performance as not need to reconnect every new query

 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();

Sign up to request clarification or add additional context in comments.

4 Comments

Now when I run this, I get the same error Error: Cannot enqueue Query after invoking quit.. Could this possibly be a DB side permission issue?
can it come from anther place in your app ? try remove the connection.end();
I tried a different query and it seems no query will work no matter where it is placed.
Fixed the issue, I was calling a connection.end() at the bottom without realizing.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.