如何在nodejs中的单个文件中提供一个mysql数据库连接 [英] How to provide a mysql database connection in single file in nodejs

查看:682
本文介绍了如何在nodejs中的单个文件中提供一个mysql数据库连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要为模块提供mysql连接。我有一个这样的代码。

I need to provide the mysql connection for modules. I have a code like this.

var express = require('express'),
app = express(),
server = require('http').createServer(app);

var mysql      = require('mysql');
var connection = mysql.createConnection({
    host     : '127.0.0.1',
    user     : 'root',
    password : '',
    database    : 'chat'
});

connection.connect(function(err) {
    if (err) {
        console.error('error connecting: ' + err.stack);
        return;
    }
});

app.get('/save', function(req,res){
    var post  = {from:'me', to:'you', msg:'hi'};
    var query = connection.query('INSERT INTO messages SET ?', post, function(err, result) {
        if (err) throw err;
    });
});

server.listen(3000);

但是我们如何为所有模块提供一次mysql连接。

But how we provide one time mysql connection for all the modules.

推荐答案

您可以创建一个db包装器,然后要求它。 node的require每次返回一个模块的同一个实例,所以你可以执行你的连接并返回一个处理程序。从 Node.js文档

You could create a db wrapper then require it. node's require returns the same instance of a module every time, so you can perform your connection and return a handler. From the Node.js docs:

每个调用require('foo')将获得完全相同的对象返回,如果它会解析到同一个文件。

every call to require('foo') will get exactly the same object returned, if it would resolve to the same file.

您可以创建 db.js

var mysql = require('mysql');
var connection = mysql.createConnection({
    host     : '127.0.0.1',
    user     : 'root',
    password : '',
    database : 'chat'
});

connection.connect(function(err) {
    if (err) throw err;
});

module.exports = connection;

然后在您的 app.js 中只需要它。

Then in your app.js, you would simply require it.

var express = require('express');
var app = express();
var db = require('./db');

app.get('/save',function(req,res){
    var post  = {from:'me', to:'you', msg:'hi'};
    db.query('INSERT INTO messages SET ?', post, function(err, result) {
      if (err) throw err;
    });
});

server.listen(3000);

此方法允许您抽象任何连接详细信息,包装任何您想要公开的内容,并要求 db 在您的应用程序中,同时保持一个连接到您的数据库,感谢节点如何工作:)

This approach allows you to abstract any connection details, wrap anything else you want to expose and require db throughout your application while maintaining one connection to your db thanks to how node require works :)

这篇关于如何在nodejs中的单个文件中提供一个mysql数据库连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆