Home > other >  What is SET and ? in mysql,nodejs
What is SET and ? in mysql,nodejs

Time:09-10

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

CodePudding user response:

? 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

CodePudding user response:

You have 2 separated things here

First is the SET clause (for the insert) that from the documentation:

A SET clause indicates columns explicitly by name, together with the value to assign each one.

link: https://dev.mysql.com/doc/refman/8.0/en/insert.html

The other part is the ? the according to the documentation of mysqljs:

... you can use ? characters as placeholders for values you would like to have escaped

link: https://github.com/mysqljs/mysql

So, the SET indicates the assignment list of the insert and the ? escapes the values.

  • Related