I created two files to test the use of MySQL with NodeJS as below, but I'm finding the answer slow and I think I'm doing something wrong:
DOUBTS :
1) Is this way to access the database the most correct? That is, every time I need to save or access something in the database, I have to create the connection with mysql.createPool
, getConnection
and execute release()
for each operation?
2) When I run retrieve
in my test.js
file, do I recover the data using same callback 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);
});