Answer the question
In order to leave comments, you need to log in
What is the best way to open and close a MySQL connection from NodeJs?
Hello.
In a project that uses NodeJs + Express on the server, I organized the opening and closing of a connection with MySql like this:
var config = {
host : 'localhost',
user : 'db_user',
password : '11111',
database : 'db_name'
};
app.get("/query-url", function (request, response) {
var db = mysql.createConnection(config);
db.connect(function (err) {
if (err) {
console.error('error connecting: ' + err.stack);
return;
}
console.log('connected as id ' + db.threadId + ' 1');
});
db.query("SELECT * FROM table_name Where id>0", function (err, rows, fields) {
if (err) return console.log(err);
response.send(rows);
});
db.end();
};
var config = {
host : 'localhost',
user : 'db_user',
password : '11111',
database : 'db_name'
};
var db = mysql.createConnection(config);
db.connect(function (err) {
if (err) {
console.error('error connecting: ' + err.stack);
return;
}
console.log('connected as id ' + db.threadId + ' 1');
});
app.get("/query-url", function (request, response) {
db.query("SELECT * FROM table_name Where id>0", function (err, rows, fields) {
if (err) return console.log(err);
response.send(rows);
});
};
Answer the question
In order to leave comments, you need to log in
Instead of these complexities, just use a connection pool (like the mysql library is used in the code). Then you won't need to manually control the closing of connections.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question