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

梦想与她 提交于 2020-01-06 06:25:33

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!