在Express 4中打开mysql连接的最佳方法

Best way to open a mysql connection in Express 4

本文关键字:连接 最佳 方法 mysql Express      更新时间:2023-09-26

所以我已经安装了node-mysql,我在express 4上运行。我是一个全新的表达,想学习数据库连接的最佳实践。我现在有

app.js

var mysql = require('mysql'); //set up mysql here
var routes = require('./routes/index');
var users = require('./routes/users');
var work = require('./routes/work');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')))
app.use('/', routes);
app.use('/users', users);
app.use('/work', work); //send the mysql var to work..?
app.use(mysql, work);

正如你所看到的,我在app.js中设置了mysql,我如何将这个变量发送到work.js。我试过:

app.use(mysql, work);

但是当我在work.js文件中访问mysql时,我得到一个错误说mysql是未定义的。

编辑:

我已经添加了var mysql = require('mysql'); //set up mysql here到我的工作。js页面,它工作得很好,我应该从app.js删除它吗?对此的最佳实践是什么?我不想每次在不同页面上查询时都打开一个新的数据库连接,对吧?

您可以在其他文件中使用mysql变量(例如用户路由):

app.js:

var mysql = require('mysql'); //set up mysql here
var users = require('./routes/users')(mysql);
var app = express();

users.js:

exports = module.exports = function (mysql) {
   console.log(mysql);
   // do what you have to do with the mysql variable
}