[英]confusion about how connection.end() works in node.js mySQL module
const mysql = require('mysql');
let connection = mysql.createConnection(...);
connection.connect((err)=>{
...
connection.query((err)=>{
...
connection.end();});
});
After I close the connection by using 在我使用关闭连接后
connection.end()
connection.end()
, if I want to query the database again using the same credentials, do I need to make a new connection by calling ,如果我想使用相同的凭据再次查询数据库,是否需要通过调用来建立新连接
mysql.createConnection(...)
mysql.createConnection(...)
Or can I reuse the same connection by simply calling 或者我可以通过简单地调用来重用相同的连接
connection.connect(...)
connection.connect(...)
A little background: I'm deploying an angular/node.js app to a shared hosting website, and the web host has a maximum limit of 25 concurrent connections to mySQL database, therefore I need to make sure I close a connection properly after a user does his query. 一点背景知识:我正在将angular / node.js应用程序部署到共享托管网站,并且该虚拟主机最大限制为25个并发连接到mySQL数据库,因此我需要确保在用户进行查询。 I am not sure if I could reuse the connection created by mysql.createConnection(...) after I close that connection, or do I need to create a brand new connection.
我不确定在关闭该连接后是否可以重用mysql.createConnection(...)创建的连接,还是需要创建一个全新的连接。
You can use one global connection for getting data from db . 您可以使用一个全局连接从db获取数据。
If You working on single file than you can write as 如果您处理单个文件,则可以写为
app.js one file only app.js仅一个文件
var mysql = require('mysql');
var connection = mysql.createConnection(...);
connection.query('SELECT 1', function (error, results, fields) {
if (error) throw error;
// connected!
});
if you want to use same connection in multiple file than you can write as 如果要在多个文件中使用相同的连接,则可以编写为
app.js app.js
app.use(
connection(mysql, {
host: xxxxx,
user: 'root',
password : xxxx,
port : 3306,
database:dbname
},'pool'),
);
var oem = require('./routes/type');
app.get('/api/oemtype',oem.type);
For the second file type.js 对于第二个文件type.js
exports.type = function(req, res){
req.getConnection(function(err,connection){
var query = connection.query('SELECT * FROM type',function(err,rows)
{
if(err)
res.json({
status:0
});
res.send(rows);
res.render('customers',{page_title:"Customers - Node.js",data:rows});
});
});
};
No need to use of connection.end(). 无需使用connection.end()。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.