T
T
timofy2019-05-13 15:59:30
MySQL
timofy, 2019-05-13 15:59:30

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();
};

that is, the connection to MySQL and its closure are registered for each request to the server. And I have a question, respectively: is it possible to open a connection to the MySql database once and not close it, or will there be problems (overloading the connection, openness for access from the outside, etc.)?
So, is it possible to write like this?
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

1 answer(s)
V
Vladlen Hellsite, 2019-05-13
@timofy

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 question

Ask a Question

731 491 924 answers to any question