gpt4 book ai didi

mysql - NPM MySql 连接需要在文件中分开

转载 作者:行者123 更新时间:2023-11-29 04:36:48 26 4
gpt4 key购买 nike

我希望使用 npm MySQL 创建到单独文件的连接。我希望每次触发查询时都将连接变量或池变量导出。如果我将它分开另一个文件,我当前的方法每次都会重新创建连接。

//连接.js

'use strict';
var mysql = require('mysql');
var sys = require('util');
var exec = require('child_process').exec;
var config = require('config');
var db_config = {
host : config.get('databaseSettings.db_host'),
user : config.get('databaseSettings.db_user'),
password : config.get('databaseSettings.db_password'),
database : config.get('databaseSettings.database'),
port : config.get('databaseSettings.mysqlPORT'),
multipleStatements: true,
debug : ['ComQueryPacket']
};
var restart = function (callback) {
console.log('RESTART THE SERVER');
callback();
//exec("whoami; pm2 restart dashboard;", callback);
};
var handleDisconnect = function () {
connection = mysql.createConnection(db_config);
console.log('\n\n\t--In the handleDisconnect from connection to DB\n');
connection.connect(function (err) {
if (err) {
console.log('--DB CONNECTION ERROR - ');
setTimeout(handleDisconnect, 2000);
} else {
console.log('connection variable created ');
}
});
connection.on('error', function (err) {
console.log('--DB CONNECTION ERROR - ');
switch (err.code) {
case 'PROTOCOL_CONNECTION_LOST':
handleDisconnect();
break;
case 'PROTOCOL_ENQUEUE_AFTER_FATAL_ERROR':
restart();
break;
default:
throw err;
}
});
};
handleDisconnect();

这样,我希望从此文件中导出连接/池连接。

最佳答案

连接.js

var mysql = require('mysql');
var db_config = {
//...
connectTimeout: 10000 //The milliseconds before a timeout occurs during
//the initial connection to the MySQL server.
};
var pool = mysql.createPool(db_config);

pool.getConnection(function(err, connection) {
// connected! (unless `err` is set)
});

pool.on('error', function(err) {
console.log(err.code); // 'ER_BAD_DB_ERROR'
// https://www.npmjs.com/package/mysql#error-handling
});

module.exports = pool;

其他文件.js

var db = require('./connection.js'); // db is pool

db.query('SELECT 12 AS number', function(err, rows, fields) {
if (err) throw err;

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

关于mysql - NPM MySql 连接需要在文件中分开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39267352/

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