mysql - 何时在 Node 中初始化 mysql 连接

标签 mysql node.js node-mysql

我试图找出在 Node 中实际初始化 mysql 连接的最佳时间是什么。

我是否应该创建一个连接池,然后将它们设置为全局连接,以便我的所有模型都可以访问该池?或者我是否应该在执行查询时初始化连接?(看起来很糟糕)。

我确信有一些“正确”的方法可以做到这一点,但我不太确定最好的方法是什么。

最佳答案

如果您要池化连接,那么不要在需要时初始化连接。当不使用池时,您可以在应用程序启动时存储连接信息,并在需要时使用它:

var mysql = require('mysql');
var connection = mysql.createConnection({
  host: 'localhost',
  user: 'me',
  password: 'secret'
});

然后对于单一用例:

connection.connect();
connection.query('SELECT 1 + 1 AS solution', function(err, rows, fields) {
  // we are done with the connection
  connection.end();

  if (err) throw err;
  console.log('The solution is: ', rows[0].solution);
});

如果您使用池化,则应该在应用程序启动时创建一个连接池,并在需要时获取连接。您不应创建多个池。

var mysql = require('mysql');
var pool  = mysql.createPool({
  host: 'example.org',
  user: 'bob',
  password: 'secret'
});

然后,当您需要连接时,您可以执行以下操作:

pool.getConnection(function(err, connection) {
  connection.query( 'SELECT something FROM sometable', function(err, rows) {
    // we are done using the connection, return it to the pool
    connection.release();

    // the connection is in the pool, don't use it here
  });
});

关于mysql - 何时在 Node 中初始化 mysql 连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18828497/

相关文章:

php - 如何设置 php 脚本来处理 2 个表

javascript - 使用 PHP 将 JavaScript 变量发布到 MySQL

mysql - 使 where 子句中同一个表中的同一列相等

css - Gruntfile.js SASS 任务配置

mysql - 如何使用 node-mysql 中的数组进行更新

mysql更新查询在一般日志中但数据没有改变

MySQL:根据计数条件更新行

node.js - 将 React/Node/Express 应用程序上传到 Heroku 后获取 "Failed to load resource: net::ERR_CONNECTION_REFUSED"

javascript - NodeJS 将数组放入 MongoDB doc.validate 不是函数

mysql - sailsjs 框架不支持事务