In nodejs, mysql connection-is it better to query and connect the database once each time, or to connect the database when starting node and disconnect it when closing?

  mysql, question

Because I used php before, I only connected every time I made a query and closed it when I finished the query. However, with nodejs, I found that it was not necessary to connect-close every query. When I started node app, I connected and then kept connected. I didn’t see any bad things in how to query. I want to ask if this is right. Or is it that different needs have different approaches?

There are two ways to solve it.
1. You can configure mysql connection pool

var mysql = require('mysql');
 var pool = mysql.createPool({
 host: 'localhost',
 user: 'nodejs',
 password: 'nodejs',
 database: 'nodejs',
 port: 3306
 });
 
 var selectSQL = 'select * from t_user limit 10';
 
 pool.getConnection(function (err, conn) {
 If (err) console.log("POOL == > "plus err);
 
 conn.query(selectSQL,function(err,rows){
 if (err) console.log(err);
 console.log("SELECT ==> ");
 for (var i in rows) {
 console.log(rows[i]);
 bracket
 conn.release();
 });
 });

2. You can use disconnection and reconnection to solve the problem.

var mysql = require('mysql');
 var conn;
 function handleError () {
 conn = mysql.createConnection({
 host: 'localhost',
 user: 'nodejs',
 password: 'nodejs',
 database: 'nodejs',
 port: 3306
 });
 
 //Connection error, try again in 2 seconds
 conn.connect(function (err) {
 if (err) {
 console.log('error when connecting to db:', err);
 setTimeout(handleError , 2000);
 bracket
 });
 
 conn.on('error', function (err) {
 console.log('db error', err);
 //If the connection is disconnected, reconnect automatically.
 if (err.code === 'PROTOCOL_CONNECTION_LOST') {
 handleError();
 } else {
 throw err;
 bracket
 });
 bracket
 handleError();