[英]How to execute MySQL queries in node.js views?
I have imported mysql
module in my app.js
: 我在
app.js
导入了mysql
模块:
var mysql = require('mysql');
Then I set mysql
configuration: 然后我设置
mysql
配置:
// Database configuration
var HOST = 'localhost';
var PORT = 3306;
var MYSQL_USER = 'root';
var MYSQL_PASS = 'pass';
var DATABASE = 'ruchevits_website';
Created mysql
client object: 创建
mysql
客户端对象:
// Create database client
var db = mysql.createClient({
host: HOST,
port: PORT,
user: MYSQL_USER,
password: MYSQL_PASS
});
And selected my database: 并选择了我的数据库:
// Use database
db.query('use ' + DATABASE);
So, now I can execute queries like: 所以,现在我可以执行以下查询:
db.query('select id, firstname, lastname from mytable', function(err, result, fields){
if (err)
{
throw err;
}
else
{
console.log('Selected people:');
for (var i in result)
{
var people = result[i];
console.log(people.firstname + ' ' + people.lastname);
}
}
});
But it is inconvenient to execute all queries in app.js
. 但是在
app.js
执行所有查询app.js
。
I want to execute them in specific routes
files in the section: 我想在以下部分的特定
routes
文件中执行它们:
exports.index = function(req, res)
{
// MySQL query
res.render('resume', {
title: 'Resume'
});
};
What is the correct way to do that? 这样做的正确方法是什么?
I need to use db
object not in app.js
file. 我需要在
app.js
文件中使用db
对象。 Actually, the question is how to pass it? 实际上,问题是如何通过它?
Create a module and export a function that returns the db object. 创建一个模块并导出一个返回db对象的函数。
in dbConnection.js
在
dbConnection.js
var mysql = require('mysql');
var db = null;
module.exports = function () {
if(!db) {
db = mysql.createClient({
host: HOST,
port: PORT,
user: MYSQL_USER,
password: MYSQL_PASS
});
};
return db;
};
use it with var db = require('./dbConnection')();
将它用于
var db = require('./dbConnection')();
where ever you need it. 你需要它的地方。 Also check out Node.js module caching feature http://nodejs.org/api/modules.html#modules_caching .
另请参阅Node.js模块缓存功能http://nodejs.org/api/modules.html#modules_caching 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.