Home  >  Q&A  >  body text

How to pass parameters to MySQL query callback function in Node.js

<p>I'm trying to figure out the correct way to pass custom data to a query call so it's available in the callback. I'm using MySQL library (all latest versions) in nodejs. </p> <p>I have a call connection.query(sql, function(err, result) {...});</p> <p>I can't find a way to 1) pass custom data/parameters to the call so it's available when the callback is called. So, what's the right thing to do? </p> <p>I have the following pseudocode: </p> <pre class="brush:php;toolbar:false;">... for (ix in SomeJSONArray) { sql = "SELECT (1) FROM someTable WHERE someColumn = " SomeJSONArray[ix].id; connection.query(sql, function (err, result) { ... var y = SomeJSONArray[ix].id; }; }</pre> <p>From the code above, I need to be able to pass the current value of "ix" used in the query to the callback itself. </p> <p>How do I do this? </p>
P粉078945182P粉078945182424 days ago617

reply all(2)I'll reply

  • P粉212971745

    P粉2129717452023-08-23 13:55:53

    To answer the initial question and illustrate with an example, wrap the callback function in an anonymous function that immediately creates a "snapshot" scope containing the incoming data.

    var ix=1;
    connection.query('SELECT 1',
        (function(ix){
            return function(err, rows, fields) {
                console.log("ix="+ix);
                console.log(rows);
            };
        })(ix));

    For those like me who are just learning this concept, the last })(ix)); is the value of the outer var ix=1 which is passed to (function(ix){. If you would console.log("ix=" abc); is changed to console.log("ix=" abc);, then it can be renamed to (function(abc){.

    fwiw (Thanks to Chris for the link, filling in the gaps to come up with the solution)

    reply
    0
  • P粉476046165

    P粉4760461652023-08-23 11:39:22

    If you are using node-mysql, please follow the instructions in the documentation:

    connection.query(
        'SELECT * FROM table WHERE id=? LIMIT ?, 5',[ user_id, start ], 
        function (err, results) {
    
        }
    );

    Code for properly escaping strings is also provided in the documentation, but using an array in a query call will automatically escape it for you.

    https://github.com/felixge/node-mysql

    reply
    0
  • Cancelreply