Search code examples
mysqlnode.jsnode-mysql

node-mysql multiple statements in one query, execute conditionally on response from each


I want to execute multiple queries in one API call, but I only want to execute them conditionally based on the response of the previous one. How can I go about implementing this?

I've seen that I can do something like below to execute multiple queries.

connection.query('SELECT * ...; SELECT * ...', [1, 2], function(err, results) {
   if (err) throw err;
});

But how do I await the response of the first before conditionally executing the second?


Solution

  • That is not supported (unless written in database itself - like tsql, plsql or others). What you can do - is execute query, wait for its results and then execute another accordingly. example:

    const query1 = '.....';
    connection.query(query1, [...params1], function(err, results) {
       if (err) throw err;
    
       const query2 = condition ? '....' : '........';
       connection.query(query2, [...params2], ......);
    });
    

    and so on in and in (callback hell).

    You can do it a bit better like that (i presume connection is: mysql.getConnection and is properly set without errors there). params<X> is an array with parameters for the query.

    
    const executeQuery = async (con, query, params) {
       return new Promise((resolve, reject) => {
          con.query(query, params, (err, result) => {
              if (err) { return reject(err); }
    
              return resolve(result);
          });
       });
    }
    
    
    mysql.getConnection((err, connection) => {
       if (err) { throw err; }
    
       try {
          const query1 = '<some query>';
          const result1 = await executeQuery(query1, params1);
    
          const query2 = (condition on query1) ? '<query>' : '<other query>';
          const result2 = await executeQuery(connection, query2, params2);
    
          const query3 = (condition you want) ? '<query for that condition>' : '<or not>';
          const result3 = await executeQuery(connection, query3, params3);
       } catch (err) {
         connection.release();
         throw err;
       } // if newest node  you can use  finally block and have only one  connection.release();
    
       connection.release();
    }