[英]Retrieving data from MySQL using Nodejs
I'm new to javascript and nodeJS. 我是javascript和nodeJS的新手。
I'm having some trouble trying to run a SQL query to retrieve data using Nodejs. 我在尝试运行SQL查询以使用Nodejs检索数据时遇到了一些麻烦。
I created a connection module (db.js) but unable to get the results from executing controller.js. 我创建了一个连接模块(db.js),但是无法从执行controller.js中获得结果。
I know for sure that the connection module is working well as I manage to retrieve data from DB if I were to swap the resolve(connection) to queries. 我可以肯定的是,如果我将resolve(connection)交换到查询中,那么我就设法从DB检索数据,因此连接模块运行良好。
Please help me take a look where did I go wrong. 请帮助我看看我哪里出错了。
Here is the db.js 这是db.js
var mysql = require('mysql2');
var Client = require('ssh2').Client;
var ssh = new Client();
var db = new Promise(function (resolve, reject) {
ssh.on('ready', function () {
ssh.forwardOut(
'127.0.0.1',
12345,
'127.0.0.1',
3306,
function (err, stream) {
if (err) throw err;
let connection = mysql.createConnection({
host: '127.0.0.1',
user: 'username',
password: 'password',
database: 'test',
stream: stream
});
connection.connect(function (err) {
if (!err) {
resolve(connection)
} else {
reject(err);
}
});
});
}).connect({
host: 'hostname',
port: 22,
username: 'username',
password: 'password'
});
});
module.exports = db;
Here is the controller.js 这是controller.js
var database = require('./db');
module.exports.getcats = (function(req, res) {
database().then(function (connection) {
connection.query("SELECT * FROM listUnit", function (error, results, fields) {
if (error) {
console.log(error);
return;
}
res.write(results);
});
});
});
If your code is as you describe it above, nothing visible will happen when you run 如果您的代码如上所述,则运行时将看不见任何内容
node controller.js
This is because your controller module defines an exported function that opens a database connection and makes a query, but it never invokes that function. 这是因为您的控制器模块定义了一个导出的函数,该函数可以打开数据库连接并进行查询,但是从不调用该函数。
Probably in a real application you would use the exported getcats()
function in some other module, like you've used the db()
function. 可能在实际的应用程序中,您将在其他模块中使用导出的
getcats()
函数,就像您曾经使用过db()
函数一样。 But, if you wanted to, you could modify your controller so that the code defines , exports , and invokes the function, giving you the result of your query when you run it from the command line: 但是,如果愿意,可以修改控制器,使代码定义 , 导出和调用该函数,从而在从命令行运行查询时为您提供查询结果:
var database = require('./db');
// define the function
function getcats(req, res) {
database().then(function (connection) {
connection.query("SELECT * FROM listUnit", function (error, results, fields) {
if (error) {
console.log(error);
return;
}
res.write(results);
});
});
}
// export the function for use in other places
module.exports = getcats;
// invoke so it runs the query when you call "node controller.js"
getcats();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.