CRUD Mysql with Nodejs: how to use Pool correctly?

Asked

Viewed 2,316 times

1

I created two file to test the use of Mysql with Nodejs as follows below, but I’m finding the answer a little slow and I think I’m doing something wrong:

DOUBTS:

1) Is this the most correct way to access the database? I mean, every time I need to save or access something in the bank mysql.createPool, getConnection and execute the release() for each operation?

2) When I execute retrievein my file test.js, I recover the data using callback even as I indicated?

model js.

var mysql = require('mysql');
var pool  = mysql.createPool({
  connectionLimit : 10,
  host     : 'localhost',
  database : 'dbtest',
  user     : 'root',
  password : '123456'
});

exports.retrieveOne = function(id, callback) {
    var sql = "SELECT * FROM test WHERE id = ?";
    var params  = [];

    params.push(id);
    sql = mysql.format(sql, params);

    pool.getConnection(function(err, connection) {
        if (err)
            console.log('Connection error: ', err);
        else
            connection.query(sql, callback);

        connection.release();
    });
}

exports.retrieveAll = function(callback) {
    var sql = "SELECT * FROM test";
    pool.getConnection(function(err, connection) {
        if (err)
            console.log('Connection error: ', err);
        else
            connection.query(sql, callback);

        connection.release();
    });
}

//exports.create = function() { }
//exports.update = function() { }
//exports.delete = function() { }

test js.

var getRow = require('./model.js');

//Retorna todos os registros
getRow.retrieveAll(function(err, rows) {
    console.log('Err: ', err);
    console.log('Rows: \n', rows);
});

// Retorna 1 registro
var id = 2;
getRow.retrieveOne(id, function(err, rows) {
    console.log('Err: ', err);
    console.log('Rows: \n', rows);
});

1 answer

1


In your model.js flames once mysql.createPool. This is correct and only happens once, when the program loads, then every call to the database uses getConnection and release.

To use Mysql return you must use asynchronous logic, you can use for example callbacks or Promisses.

If you do this to Predomises I could stay like this:

model js.

exports.retrieve = function(id) {
  var sql = "SELECT * FROM test WHERE id = ?";
  var params = [];
  params.push(id);
  sql = mysql.format(sql, params);

  return new Promise(function(res, rej) {
    pool.getConnection(function(err, connection) {
      if (err) rej(err);
      connection.query(sql, function(err, rows) {
        if (err) rej(err);
        else res(rows);
        connection.release();
      });
    });
  });

}

js test.

getRow.retrieve('4').then(rows => {
    console.log(rows);
})
  • 1

    Sergio, this is perfect!! This is EXACTLY what I needed, because I am not returning the results to the browser but to another script that will manipulate the data. Just for the record, I edited my question and presented the way I was already doing (which also worked...). I’ll use it the way you indicated, because I believe it’s more correct than mine.

  • @wBB you can use as you had too. Promisses are safer in case of error as they do not stop the server, the error is controlled otherwise. Glad I could be of service.

  • Oh yes, yes doubt. I was even using the error handling I added to your code: getRow.retrievePromise('4').then(_success, _error); performing correctly function _success(data) {
 console.log('DATA: ', data); } and in case of error function _error(err) {
 console.log('ERROR: ', err); }

  • by kindness @Sergio, I have a question about the issue of connection: I create a file the part called "Conn.js" for example, in which mount the connection var mysql = require('mysql'); and var pool = mysql.createPool({......etc, etc. Then I do the require('./conn') in all other files where I will access the database. With this, throughout require I am opening a new connection instead of reusing an existing connection, it is not?

  • @wBB depends on how that file looks. If export only from pool then only creates 1 time. Each require does not run the whole code again. Test put a console.log('lalala'); in the file conn.js off export and inside export and you will see that what is outside export is only called 1 time.

  • I swear I tried it here, but I couldn’t put together a way that the creation of a new connection is executed once and then available for use. I even tried to use the console('DENTRO') and console('FORA') to be able to record what was happening, but the thing didn’t work...

  • @wBB in question you have a file model.js. That one var pool = mysql.createPool.. is only run once, no matter how many times you require of that file.

  • I will consider your guidelines and follow this way of the model.js even then (the consoles.log(dentro/fora) used between these codes). I kept const mysql = require('mysql'); const pool = mysql.createPool({...etc then the Xports exports.retrieveA = function(callback) {...etc, etc Thank you very much for your help!

  • Everything worked OK and got fast @Sergio. Thanks!

Show 4 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.