旨在减少不必要的麻烦,避免因程序多次调用接口产生重复数据和开销。
INSERT into user_ceshi(username,password) SELECT '张三','123456' FROM DUAL WHERE NOT EXISTS
(SELECT username,password FROM user_ceshi WHERE username='张三' AND password ='123456')
js中用变量替换的方法,这里用的是express
方法一:模板字符串替换变量
function insert(username.password) {
return new Promise((resolve, reject) => {
let sql= `INSERT into user_ceshi(username,password) SELECT ${username},${password} FROM DUAL WHERE not EXISTS(SELECT username,password FROM user_ceshi WHERE username=${username} AND password =${password})`
mysqldb.query(
sql,
(err, result) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
);
});
}
方法二:使用?
function insert(username,password) {
return new Promise((resolve, reject) => {
let sql="INSERT into user_ceshi(username,password)
SELECT ?,? FROM DUAL WHERE not EXISTS
(SELECT username,password FROM user_ceshi WHERE username=? AND password =?)" mysqldb.query(
sql,
[
username,
password,
username,
password
],
(err, result) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
);
});
}