gpt4 book ai didi

javascript - 如何使 node.js mysql 连接池在启动时可用

转载 作者:行者123 更新时间:2023-11-29 03:59:43 26 4
gpt4 key购买 nike

每次我的 showData.js 脚本运行时它调用

var pool  = mysql.createPool({

有没有办法在 node.js 服务器启动时创建连接池?

我已经尝试将 createPool 添加到 server.js,但我似乎无法在调用时从我的 showData.js 脚本访问该对象

pool.getConnection(function(err,connection){

是否有必要在 node.js 服务器启动时启动连接池?

即使在调用 connection.release 和脚本关闭后,mysql 连接池是否仍然存在

编辑 @Marco,我收到ReferenceError: pool is not defined. 我知道问题是我没有将池拉入showData.js。按照 node.js 的说法,多次加载一个模块是可以的。

来自 https://nodejs.org/api/modules.html

Caching

Modules are cached after the first time they are loaded. This means (among other things) that every call to require('foo') will get exactly the same object returned, if it would resolve to the same file.

Multiple calls to require('foo') may not cause the module code to be executed multiple times. This is an important feature. With it, "partially done" objects can be returned, thus allowing transitive dependencies to be loaded even when they would cause cycles.

If you want to have a module execute code multiple times, then export a function, and call that function.

这是我的最新设置:

lib/dbpool.js

var mysql = require('mysql');
var pool = mysql.createPool({
connectionLimit : 10,
host : 'someco.com',
user : 'pinco',
password : 'pallino'
});

module.exports = pool;

服务器.js

const pool = require('./lib/dbpool');

显示数据.js

'use strict';
module.exports = router => {
router.route('/show').post((req, res) => {
pool.query('SELECT * FROM db.users', function(err, rows, fields) {

我是否需要在 server.js 和 showData.js 中添加以下行?

const pool = require('./lib/dbpool');

最佳答案

使用以下内容定义一个名为 lib/dbpool.js 的模块:

var mysql = require('mysql');
var pool = mysql.createPool({
connectionLimit : 10,
host : 'someco.com',
user : 'pinco',
password : 'pallino'
});

module.exports = pool;

然后在您的应用代码中使用:

const pool = require('./lib/dbpool');

app.post('/your/app/url', (req, res) => {
pool.query('your query', function(err, rows, fields) {
if (err) throw err;
/* Manage your results here */

});
}

pool.query实际执行:pool.getConnection()然后connection.query()然后connection.release()

关于javascript - 如何使 node.js mysql 连接池在启动时可用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44230641/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com