Search code examples
mysqlnode.jssyntaxdocumentationfaker

How to use placeholders while inserting data in MySql database using nodejs?


let r={ email:faker.internet.email() } ;
connection_var.query("insert into users set ?",r, function(err,res){
    if(err) throw err;
    console.log(res);
} );

connection_var.end();

I wrote this code to insert a fake email addr in already existing database and into the users table just the problem is I am not fully able to understand what and how does the " SET ?" work and how is it relating to r and what if r has more than 1 key-value pairs


Solution

  • ? is a placeholder. It gets replaced with all the keys and values in the object passed as the next argument. So if you have

    let r = {col1: 1, col2: "abc", col3: 999};
    

    the query will become

    insert into users set col1 = 1, col2 = 'abc', col3 = 999