我试图找出在 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/