I have a such structure in my express app:
- db helper, that i use to interacts to my maria db
code:
var MariaSQL = require('mariasql');
var db = new MariaSQL();
var queries = {
getUserByID : 'SELECT * FROM user WHERE id=:id',
getUserByUsername : 'SELECT * FROM user WHERE username=:username'
};
module.exports = {
connect : function(config){
db.connect({
host : config.maria.host,
user : config.maria.user,
password : config.maria.password,
db : config.maria.db
});
db.on('connect', function() {
console.log('Successfully connected to DB');
})
.on('error', function(err) {
console.log('Connection error: ' + err);
})
.on('close', function(hadError) {
console.log('Client closed');
});
},
executeQuery : function(queryName, queryData, callback){
var data = queryData || {};
var result = [];
var error;
if(queryName in queries){
var pq = db.prepare(queries[queryName]);
db.query(pq(data))
.on('result', function(res) {
res.on('row', function(row) {
result.push(row);
})
.on('error', function(err){
error = err;
})
.on('end', function(info) {
//console.log('Result finished successfully, numRows = ' + info.numRows + ', insertid=' + info.insertId);
});
})
.on('end', function() {
if(error)
callback(error);
else
callback(null, result);
});
} else {
callback(new Error('Wrong query with name = ' + queryName));
}
}
};
In my app.js i call
db_helper.connect(config);to initialize connectionThen i just call
executeQuerymethod of db_helper to execute queries and get results, f.e.:db_helper.executeQuery('getUserByUsername', {username : username}, function(err, user){ ... });
So, i have some very important questions for me:
- Is it normal way to organize interaction with DB?
- Why i have multiple messages
Successfully connected to DB? After all, I call this method only once, when i initilize connection, is not it? - As I understand author closes connection each time all date recieved using method
c.end(). But can i not to close connection and use opened one?
p.s. Sorry for my english... And thanks for help, it's my first question :)