noddy asked this 2 years ago

NodeJS Cannot enqueue Handshake after already enqueuing a Handshake

I am trying to insert into MYSQL table some data recieved from AJAX post.

Error: Cannot enqueue Handshake after already enqueuing a Handshake.

    at Protocol._validateEnqueue (C:\nodejs\node_modules\mysql\lib\protocol\Protocol.js:208:16)

    at Protocol._enqueue (C:\nodejs\node_modules\mysql\lib\protocol\Protocol.js:135:13)

    at Protocol.handshake (C:\nodejs\node_modules\mysql\lib\protocol\Protocol.js:52:41)

    at Connection.connect (C:\nodejs\node_modules\mysql\lib\Connection.js:136:18)

    at C:\nodejs\myindex.js:28:13

    at Layer.handle [as handle_request] (C:\nodejs\node_modules\express\lib\router\layer.js:95:5)

    at next (C:\nodejs\node_modules\express\lib\router\route.js:131:13)

    at Route.dispatch (C:\nodejs\node_modules\express\lib\router\route.js:112:3)

    at Layer.handle [as handle_request] (C:\nodejs\node_modules\express\lib\router\layer.js:95:5)

    at C:\nodejs\node_modules\express\lib\router\index.js:277:22

 

 

The code I am using is

var mysql = require('mysql')
var connection = mysql.createConnection({
  host: 'localhost',
  user: 'myusername',
  password: 'mypassword'
})

function insertData(name,id) {

  connection.connect();

  console.log(name+' '+age)
  connection.query('INSERT INTO members (name, id) VALUES (?, ?)', [name,id], function(err,result) {
	  if(err) throw err
  });

  connection.end();


}

app.post('/', function(req, res) {
	
	insertData(req.body.name,req.body.id);
        //Rest of the code

});

 


sonja 2 years ago
5 likes

Do not connect() and end() inside the function. This will cause problems on repeated calls to the function. Make the connection only

var connection = mysql.createConnection({
	  host: 'localhost',
	  user: 'node',
	  password: 'node',
	  database: 'node_project'
	})

connection.connect(function(err) {
	if (err) throw err
	
});

once and reuse that connection.

 

Inside the function 

function insertData(name,id) {

  connection.query('INSERT INTO members (name, id) VALUES (?, ?)', [name,id], function(err,result) {
	  if(err) throw err
  });


}

Guest 6 months ago

Here I have a simple class for MySQL connection and query

class DatabaseMySQL {

    constructor(db) {

        const stringConexaoDB = {host:'localhost', user:'root', password:'123456', database:db}

        this.connection = mysql.createConnection(stringConexaoDB);

        console.log('Conectado ao Banco', db);

    }


    query(sql, args) {

        return new Promise((resolve, reject) => {

            this.connection.query(sql, args, (err, rows) => {

                if (err) return reject(err);

                resolve(rows);

            })

        })

    }


    close() {

        return new Promise((resolve, reject) => {

            this.connection.end(err => {

                if(err) return reject(err);

                resolve();

            })

        })

    }

}


module.exports = DatabaseMySQL;


****** I have a funExec () function; *********

function funExec() {

    db.query('SELECT * FROM DB_ICADIS.CLIENTE ORDER BY cli_codigo')

        .then(rows => {     

             rows.forEach((row) => {                               

                 funRegistroCli(row);                        

             })

             db.close();                      

        })

        .catch((error) => {

            console.log(error)

           db.close();

       })

}

*********************************************** 

When I run the function Wheel normally and after the execution of the rows, closes the connection everything ok!


NOW WHEN I EXECUTE WITHIN A ROUTE EXPRESS AS BELOW:  


*********************************************** 


rotaCliente.get('/cliente', async (req, res, next) => {

    await funExec();

    res.json({ola:"terminei"});

});


***** 


76/5000

For not having closed the bank, when having the second time, gives the following error: