Store sql query

0

Good afternoon, could anyone help me on node.js? My question is how could I store the values of a sql query in a variable as an example.

 let id = connection.query('SELECT * FROM marca ORDER BY id DESC LIMIT 1', function(err,result){
      if(err)
        throw err;
      else{
         id = result[0];
         console.log("ID!!: "+id.id);
       }
      });
    
asked by anonymous 28.03.2018 / 17:46

2 answers

0

Take a look at the documentation Escaping query values . Your alternatives are:

1. Use the methods mysql.escape() , connection.escape() or pool.escape()

var userId = 'some user provided value';
var sql    = 'SELECT * FROM users WHERE id = ' + connection.escape(userId);
connection.query(sql, function (error, results, fields) {
  if (error) throw error;
  // ...
});

2. Use the ? character as placeholder

connection.query(
  'SELECT * FROM users WHERE id = ?',
  [userId],
  function (error, results, fields) {
    if (error) throw error;
    // ...
});

In your case, you can do something like this

var post  = {id: 1, title: 'Hello MySQL'};
var query = connection.query(
  'INSERT INTO posts SET ?',
  post,
  function (error, results, fields) {
    if (error) throw error;
    // ...
});
console.log(query.sql); // INSERT INTO posts SET 'id' = 1, 'title' = 'Hello MySQL'
    
28.03.2018 / 18:43
0

Victor, let me get this straight. You want to store the result of the SQL query, in a variable to use later, right?

I believe a promise can solve this situation:

const consulta = () => {

 return new Promise((resolve, reject) => {

   const query = 'SELECT * FROM marca ORDER BY id DESC LIMIT 1';  

   connection.query(query, (err, result) => {

     if(err){

       return reject(err);
     }

     return resolve(result);
   })
 }
})

consulta().then(result => {

  console.log('ID: ${result.id}');
}).catch(err => {

  throw err;
});

In this case, consulta is a promise of the query in the database. When calling a promise , we have two arguments: Resolve and Reject .

The functions resolve and reject , when calls, resolve (on success) or reject (when an error occurs) the promise respectively.

    
30.03.2018 / 23:10