简体   繁体   中英

Nodejs and MySQL, How to use NodeJs variable in MySQL INSERT statement

So basically, I have this JavaScript variable which stores this certain value, and I need to put this variable in MySQL Query statement.

Source Code:

var Pollution_Reading = 25;
DatabaseConnection.query('INSERT INTO Air_Pollution_Record (Air_Pollution_Reading) VALUES ('"Pollution_Reading"')');

I've tried every way that I know, but I still can't insert the value that the variable is holding into the database. What should I do?

DatabaseConnection.query('INSERT INTO Air_Pollution_Record (Air_Pollution_Reading) VALUES ('+Pollution_Reading+')');

Try doing this:

//reading  post data
const useremail = req.body.useremail;
const password = req.body.password;
//save into db start
var sql = "INSERT INTO `users` (`UserName`, `UserPassword`) VALUES ('"+useremail+"','"+ password+"')";

you can try this format of template literals . Gives you Easy and Clean code.

const sql = `INSERT INTO query_form (name, email, query_title, query_description) VALUES ('${name}', '${email}', '${query_title}', '${query_description}')`;

const sql = "INSERT INTO users ( UserName , UserPassword ) VALUES ('"+useremail+"','"+ password+"')";

This method and also above are good but naive if you have quotes in your input variable like single or double quotes. It will match the single quote with the input string and you will get error as it will not consider the remaining input.

So, after a long painful research I found a fix for quotes input strings as well. The solution is to not use values front hand and pass them inside con.query() method directly.

let query = `INSERT INTO gfg_table 
        (name, address) VALUES (?, ?);`;
  
    // Value to be inserted
    let userName = "Pratik";
    let userAddress = "My Address";
  
    // Creating queries
    db_con.query(query, [userName, 
    userAddress], (err, rows) => {
        if (err) throw err;
        console.log("Row inserted with id = "
            + rows.insertId);
    });

Reference:

https://www.geeksforgeeks.org/node.js-mysql-insert-into-table/

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