【问题标题】:How i am supposed to call a mysql database using node.js and exports?我应该如何使用 node.js 调用 mysql 数据库并导出?
【发布时间】:2016-05-08 20:51:19
【问题描述】:

我正在使用 mysql 数据库开发带有 node.js、express 等的 API。我正在使用 node-mysql 连接并在我的数据库上执行查询。

为了有一个干净的代码,我把它分成了控制器和模型。但我正面临着这个:

models/user.js

var mysql      = require('mysql');
var connection = mysql.createConnection({
  host     : 'localhost',
  port     : 3307,
  user     : 'root',
  password : 'root',
  database : 'db'
});

User.prototype.blablabla = function() {
...
connection.query(...);
}

models/admin.js

var mysql      = require('mysql');
var connection = mysql.createConnection({
  host     : 'localhost',
  port     : 3307,
  user     : 'root',
  password : 'root',
  database : 'db'
});

Admin.prototype.blablabla = function() {
...
connection.query(...);
}

问题是我必须在每个文件上创建到我的数据库的连接,即使我只想调用一个,当我完成后,我关闭它。

但是通过这种配置,使用我的控制器使用回调和东西,我无法关闭连接。它一直在运行。

我正在寻找一种仅使用与数据库连接的一个实例的安全方法。这是一个好方法吗?我怎样才能做到这一点?

【问题讨论】:

    标签: javascript mysql node.js node-mysql


    【解决方案1】:

    你要不要为这个连接信息创建一个特定的文件?

    /connection.js

    var mysql      = require('mysql');
    var connection = mysql.createConnection({
      host     : 'localhost',
      port     : 3307,
      user     : 'root',
      password : 'root',
      database : 'db'
    });
    
    module.exports = connection;
    

    因为 require 会缓存它加载的模块,所以连接只会打开一次。参考http://fredkschott.com/post/2014/06/require-and-the-module-system/

    然后,注意要关闭连接,可以使用连接实例及其方法end

    connection.end();
    

    参考https://github.com/felixge/node-mysql

    【讨论】:

    • 好的,谢谢。我正在使用 express.Router(),你知道如何在每个请求之前连接.open(),然后在它之后关闭它吗?
    • 文档说However, a connection can also be implicitly established by invoking a query:ref。要在每次请求后关闭它,请以 morgan 为例并查看 this
    • 我不明白你为什么给我这些链接
    猜你喜欢
    • 2012-02-09
    • 2017-09-02
    • 1970-01-01
    • 2013-03-31
    • 2011-01-24
    • 2015-09-09
    • 2012-04-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多