报错“sqlMessage“:“Unknown column ‘xxx‘ in ‘where clause‘“ 本是古典 何须时尚 2024-04-03 08:15 32阅读 0赞 ## 问题描述 ## 在用node搭建服务器时,写了段sql语句,但是在执行时总是报错; Error: ER_BAD_FIELD_ERROR: Unknown column 'zhangsan' in 'where clause' 使用Promise的catch捕获异常后,打印出如下结果: code: 'ER_BAD_FIELD_ERROR', errno: 1054, sqlMessage: "Unknown column 'zhangsan' in 'where clause'", sqlState: '42S22', index: 0, sql: "select * from blogs where 1=1 and author=zhangsan and title like '%标题%'" 原sql相关片段: const getList =(author,keyword)=>{ //这里的 1=1 是为了防止url中没有author,keyword这两个参数所造成的报错。 //注意where的每个条件之前前要加and;之后要加空格(最后一个不用加) let sql = `select * from blogs where 1=1 `; if(author) { sql+=`and author=${author} `; } if(keyword) { //模糊查询 sql+=`and title like '%${keyword}%'`; } return execSQL(sql); } ## 解决思路 ## 起初我还以为是数据库对字符有什么编码格式要求(原来author的值是“张三”,后面改成英文,发现没啥用); 后来发现其实就是在sql中没有给author加引号: 正确写法: sql+=`and author='${author}' `; 错误写法: sql+=`and author=${author} `; 备注:感觉这个错误非常经典,在此记录,下不再犯。
还没有评论,来说两句吧...