简体   繁体   中英

How to use one Mysql pool connection in many files in a NodeJS Express App

I've been scratching my head at this. I wanted to know if there was an efficient way of creating one Mysql connection and sharing it between different modules in an application served by Express. So far I have the following code at the top in all my JS files that require a database connection of sorts:

const db = require('mysql2')
pool = db.createPool(<config details>)

// Below
pool.execute(.. ) // etc

I feel like this is an overkill. Is there a way to create one connection, say in express app? Or a separate file and then retrieve that connection whenever I need it? I am thinking something like:

// In db.js
const db = require('mysql2')
module.exports = db.createPool(<config details>)

// In file1.js that needs a db connection
let db = require('./db')
db.execute(...)

// In file2.js
let db = require('./db')
db.execute(...)

And so on. Thanks for the help guys.

Well, I figured it out thanks to @paul. I created a dB file where I placed the MySQL connection and exported it so that other files that need the connection could simply require it.

// dB.sql
let MySQL = require(‘mysql2’)
module.exports = MySQL.createPool(require(‘./config’)

So any file that includes the file above will have access to the connection.

// File that needs pool instance
let pool = require(‘path to dB file’)

I hope this helps anyone that's looking for a similar solution.

Cheers!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM