报错“sqlMessage“:“Unknown column ‘xxx‘ in ‘where clause‘“

本是古典 何须时尚 2024-04-03 08:15 221阅读 0赞

问题描述

在用node搭建服务器时,写了段sql语句,但是在执行时总是报错;

  1. Error: ER_BAD_FIELD_ERROR: Unknown column 'zhangsan' in 'where clause'

使用Promise的catch捕获异常后,打印出如下结果:

  1. code: 'ER_BAD_FIELD_ERROR',
  2. errno: 1054,
  3. sqlMessage: "Unknown column 'zhangsan' in 'where clause'",
  4. sqlState: '42S22',
  5. index: 0,
  6. sql: "select * from blogs where 1=1 and author=zhangsan and title like '%标题%'"

原sql相关片段:

  1. const getList =(author,keyword)=>{
  2. //这里的 1=1 是为了防止url中没有author,keyword这两个参数所造成的报错。
  3. //注意where的每个条件之前前要加and;之后要加空格(最后一个不用加)
  4. let sql = `select * from blogs where 1=1 `;
  5. if(author) {
  6. sql+=`and author=${author} `;
  7. }
  8. if(keyword) {
  9. //模糊查询
  10. sql+=`and title like '%${keyword}%'`;
  11. }
  12. return execSQL(sql);
  13. }

解决思路

起初我还以为是数据库对字符有什么编码格式要求(原来author的值是“张三”,后面改成英文,发现没啥用);

后来发现其实就是在sql中没有给author加引号:

正确写法:

  1. sql+=`and author='${author}' `;

错误写法:

  1. sql+=`and author=${author} `;

备注:感觉这个错误非常经典,在此记录,下不再犯。

发表评论

表情:
评论列表 (有 0 条评论,221人围观)

还没有评论,来说两句吧...

相关阅读