简体   繁体   中英

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

In my controller I am writing this code

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' } ]

in my model class I am executing my 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

Try to pass params to your fetchUser method

  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:

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)
    })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM