I'm building an Node application which will query simple and more complex (multiple joins) queries. I'm looking for suggestions on how I should manage the mySQL connections.
I have the following elements:
//this is router1 router.get('/', function (req, res){ connection.connect(function(Err){...}); connection.query('SELECT* FROM table WHERE id = "blah"', function(err,results,fields){ console.log(results); }); ... connection.end(); })
Should I connect to mysql everytime '/router1/' is requested, like in this example, or it's better to leave one connection open one at start up? As:
connection.connect();outside of:
router.get('/',function(req,res){ ... });?
The best practice for database connections is the same regardless of the language used. You have a pool of open connections at the start of your application. You take a connection from the pool as late as possible. Return it to the pool as soon as possible.
To use multiple database in a single Node. js project with Mongoose, we can use the connection's model method. const conn = mongoose. createConnection('mongodb://localhost/testA'); const conn2 = mongoose.
I am using mysql2 for this, it is basicly mysql but with promises. If you use mysql you can also do this.
Create a seperate file called connection.js or something.
const mysql = require('mysql2');
const connection = mysql.createPool({
host: "localhost",
user: "",
password: "",
database: ""
// here you can set connection limits and so on
});
module.exports = connection;
Then it is probaly better you create some models and call these from within your controllers, within your router.get('/', (req, res) => {here});
A model would look like this:
const connection = require('../util/connection');
async function getAll() {
const sql = "SELECT * FROM tableName";
const [rows] = await connection.promise().query(sql);
return rows;
}
exports.getAll = getAll;
You can do this with or without promises, it doesn't matter. Your connection to the pool is automatically released when the query is finished. Then you should call getAll from your router or app.
I hope this helped, sorry if not.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With