Daniel McCrevan
Daniel McCrevan

Reputation: 179

NodeJS mysql not inserting into table

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?

Upvotes: 1

Views: 2355

Answers (1)

Amit Wagner
Amit Wagner

Reputation: 3264

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

Upvotes: 1

Related Questions