简体   繁体   中英

How to get data from response of Mysql connection

I want to know whether there is any existing user with emailid in my db by the name say xyz@abc.com .

function isDuplicateUser(emailId)
{
  var sql='SELECT count(*) FROM UserDetails WHERE emailId ="'+emailId+'";';
  var con = mysql.createConnection({
    host:"localhost",
    user: "root",
    password: "32577488",
    database:"mydb"
  });
  con.connect(function(err) {
    con.query(sql, function (err, result) {
      if (err) throw err;
      console.log("Inside Duplicate check");
      console.log(result[0]);
      console.log(result.count);
      console.log(result[0].emailId);
      console.log(result[0].count);
      console.log("1 record inserted");
    });
  });
}

But in all the console.log statements I am getting undefined ! I thought of using count so that if there is more than 0 than there exists a user with that userid ! Please help me ! I have another doubt also It is ok to get connection in every function ! Like for signup have a

    function signup(email,password,name)
    {
       var sql =''....;
       //getting connection once

    }
function signin(emailid,password)
{
    //getting connection here 
    return success;
}

It seems like code is getting replicated many times !

please, try with this sql statement and let me know the result:

// replace your var sql with this one
const sql = `SELECT count(*) FROM UserDetails WHERE emailId = '${emailId}'`;

In the other hand, regarding how to manage connection in each function, my recommendation is create a pool of connections in your app and get a connection from the pool on each function you need (you need to take care about releasing the connection when you finish to make them available for new incoming requests):

// connection first time when node starts
const options = {
  connectionLimit: 10,
  host: HOST,
  user: USER,
  password: PASSWORD,
  database: DATABASE,
  port: 3306,
  timezone: 'Z',
  // debug: true,
  multipleStatements: true,
  // ...azureCertificate && sslOptions,
};

const pool = mysql.createPool(options);

// on each function, get a connection from the pool using this function
getConnection() {
  return new Promise((resolve, reject) => {
    if (pool === null) {
      return reject(new Error(`MySQL connection didn't established. You must connect first.`));
    }

    pool.getConnection((err, connection) => {
      if (err) {
        if (connection) {
          connection.release();
        }

        return reject(err);
      }

      return resolve(connection);
    });
  });
}

Hope this helps.

This example was made using npm package mysql : https://www.npmjs.com/package/mysql

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