Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

428
Vistas
mysql insert not working in node js

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.
});
over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

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)
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda