Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
146 views
in Technique[技术] by (71.8m points)

mysql - putting vars in sql query

New to Node development.

How do you put a variable in a sql query for the VALUES part. Here is what I have. Let me know if it will work.

  let email = req.body.email;
  let number = req.body.number;

  var sql = "INSERT INTO userdata (email, number) VALUES (email, number)";

Thanks

Also, second question. is there anyway I can check if a record already exists with the same email or number within the one sql statement.

question from:https://stackoverflow.com/questions/65865948/putting-vars-in-sql-query

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

According documentation, You should to use parametrized query like:

const email = req.body.email;
const number = req.body.number;

const sql = "INSERT INTO userdata (email, number) VALUES (?, ?)";

connection.query(sql, [ email, number ], 

    function (err, results) {

    }
);

About second question: If you want to your table will have unique records fro each email/number pair you should to add unique index based on those fields.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...