方法"/>
构建mysql + nodejs + express应用的最佳方法
我使用mysql(没有序列号),通常在module.export函数中创建连接,然后从其他文件中要求它,例如:
var db;
module.exports={
getConnection = function (){return new Promise(function(resolve, reject){
// db = mysql connection stuff
resolve(db)
});},
//other database related operations similarly
}
现在,我想将所有内容分开,例如,我想要一个userModel,它将具有一些与用户相关的数据库操作,这些操作将仅导入db连接,依此类推;但是实现这一目标的最佳方法是什么?谢谢。
回答如下:由于它的使用范围很广,并且不存在变量命名冲突的高风险,所以我更喜欢将其添加到全局对象中。然后,您不必确保已将其包含,传递或从模块中导入。
请考虑以下示例:
// in your application initialization file such as app.js
// require items …
const mysql = require('mysql');
const connection = mysql.createPool({
connectionLimit: 10,
host: process.env.DB_HOST || '127.0.0.1',
user: process.env.DB_USER || 'local_user',
password: process.env.DB_PASSWORD || 'local_password',
database: process.env.DB_NAME || 'local_database',
multipleStatements: true,
charset: 'utf8mb4' // necessary if you might need support for emoji characters
});
connection.on('connection', function (connection) {
// handy for testing
console.log('Pool id %d connected', connection.threadId);
});
connection.on('enqueue', function () {
// handy for testing
console.log('Waiting for available connection slot');
});
// make the connection global via the the variable db
global.db = connection;
// everywhere else in your app, use the now global db variable when running queries
db.query(
'INSERT INTO users SET ?', [{name: "John Smith"}], function(error, results, fields) {
if (error) throw error;
console.log(results);
});
}
更多推荐
构建mysql + nodejs + express应用的最佳方法
发布评论