问题
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.
回答1:
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!
来源:https://stackoverflow.com/questions/51409922/how-to-use-one-mysql-pool-connection-in-many-files-in-a-nodejs-express-app