NodeJS中MySql的增删改查操作

时间:2022-08-11 09:20:40

纯粹记录一下最基础写法,几乎没有写什么逻辑,写法也并不是很完善(因为我自己也刚刚摸索出来这么写可以...= =!)    望高手指教   也希望能够帮到比我还新的新手....

//1.insert操作

let insertSql = 'insert into User(username,password,name,gender,age) values (?,?,?,?,?)';
let insertParams = [username, password, name, gender, age];
mysqlConnection.query(insertSql, insertParams, function (error, results, fields) {
  if (error)  throw error;
  return results;
});
//2.select操作(我自己测试的时候发现,字符串类型的列,要给参数额外增加引号,否则会被当做数字类型或列名来进行处理)
let selectSql = 'select id from User where username = \''.concat(username, '\' and password = \'', password, '\'');
mysqlConnection.query(selectSql, function (error, results, fields) {
  if(error) throw error;
  return results;
});
//3.delete操作
let deleteSql = 'delete from user where id = \''.concat(id, '\'');
mysqlConnection.query(deleteSql, function (error, results, fields) {
  if (error) throw error;
  return results;
});
//4.update操作
let updateSql = 'update User set age = 30 where id = \''.concat(id, '\'');
mysqlConnection.query(updateSql, function (error, results, fields) {
  if (error) throw error;
  return results;
});