[英]How to get values from mysql database using node js
I am working on a node js application and using DB as mysql what I am trying to do is when I run a query and all data is fetched I want to access the data or store that data to variables for further use我正在开发一个节点 js 应用程序并使用 DB 作为 mysql 我想要做的是当我运行查询并获取所有数据时我想访问数据或将该数据存储到变量以供进一步使用
In my controller I am writing this code在我的 controller 我正在写这段代码
exports.login = function(req, res) {
User.fetchUser()
.then(([rows]) => {
console.log(rows)
})
.catch(err => console.log(err));
} }
this one is printing on console like [ BinaryRow { email: 'draj.8126@gmail.com', password: 'dheeraj' } ]
这个正在控制台上打印,例如[ BinaryRow { email: 'draj.8126@gmail.com', password: 'dheeraj' } ]
in my model class I am executing my fetchUser
function在我的 model class 我正在执行我的fetchUser
function
static fetchUser() {
const email = 'draj.8126@gmail.com'
const password = 'dheeraj'
let sql = 'SELECT email,password FROM tpconsumer where email = ? and password = ?'
return db.execute(sql, [email, password]);
}
Now what I am trying to do is get email and password values and store them in variable for further use, or simply how can I use email or my password I want to access them现在我要做的是获取 email 和密码值并将它们存储在变量中以供进一步使用,或者只是我如何使用 email 或我想访问它们的密码
Try to pass params to your fetchUser method尝试将参数传递给您的 fetchUser 方法
exports.login = function(req, res) {
User.fetchUser(email,password)
.then(([rows]) => {
if(rows.length >0)
{
for(var i=0; i<rows.length; i++){
console.log(rows[i].email);
console.log(rows[i].password);
}
}
else{
console.log('Nothing to fetch');
}
})
.catch(err => console.log(err));
And in your Class Model:在您的 Class Model 中:
static fetchUser(email,password) {
/*const email = 'draj.8126@gmail.com'
const password = 'dheeraj'*/
//pass your data dynamically
let sql = 'SELECT email,password FROM tpconsumer where email = ? and password = ?'
return db.execute(sql, [email, password]);
}
The result we get after executing query will be an array.我们执行查询后得到的结果将是一个数组。 so please try this所以请试试这个
user.fetchUser().then(rows => {
console.log(rows);
var email = rows[0].email;
var passw = rows[0].pass;
console.log("email--",email);
console.log("passw--",passw);
}).catch(err => {
console.log(err)
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.