简体   繁体   中英

Node.js MYSQLparse error

I have the following code

db.query("SELECT * FROM ?", [req.params.Tables_in_my_db], function(error, rows, fields) {
    if (error)
        throw error;

    //code...

    db.end();
});

When I run this code I get the following error

Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''Copy'' at line 1

However, if I log in the console req.params.Tables_in_my_db, I get the String Copy. How can I solve this issue?

Thank you.

I guess "?" will only work with values to be substituted, (SELECT * FROM table_name WHERE column_name=?), if you want to have a dynamic table, use if statement and concatenate your desired table to the string, then pass that string to the first param of db.query().

var query = "SELECT * FROM";
if (req.params.table_code == 1) {
     query += " your_desired_table";
} else if (req.params.table_code == 2) {
     query += " another_desired_table";
} else {
     //return an error here to avoid sql injection, use a code for each of 
     //the table you only want to use
}

db.query(query, ....

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