将数据库查询结果变量带引号传入MySQL查询遇1054错误求助
问题描述
执行第二个MySQL查询时抛出errno: 1054错误,生成的SQL语句为SELECT ttday, ttfrom, tttill, ttuniqueid FROM timetables where ttname = Always。手动给Always添加引号后查询可正常执行,但无法将第一个查询返回的变量codetimetable.usertimetable以带引号的形式传入第二个查询。
代码示例
async function singledbentry(sql) { const [stripDbInfoLayer] = await pool.query(sql) return stripDbInfoLayer[0] } async function activetime(inputusercode) { var sql1 = 'SELECT usertimetable FROM users where usercode =' + inputusercode; let codetimetable = await singledbentry(sql1); console.log(codetimetable); console.log(codetimetable.usertimetable); var sql = 'SELECT ttday, ttfrom, tttill, ttuniqueid FROM timetables where ttname = ' + codetimetable.usertimetable; timetabledata = await singledbentry(sql); console.log(timetabledata); console.log(timetabledata.usertimetable); } activetime('4310')
控制台错误信息
Error: Unknown column 'Always' in 'where clause'
at PromisePool.query (C:\Node JS\Projects\user-management\node_modules\mysql2\promise.js:351:22) at singledbentry (C:\Node JS\Projects\user-management\timeprogram.js:29:43) at activetime (C:\Node JS\Projects\user-management\timeprogram.js:124:27) at process.processTicksAndRejections (node:internal/process/task_queues:95:5) { code: 'ER_BAD_FIELD_ERROR', errno: 1054, sql: 'SELECT ttday, ttfrom, tttill, ttuniqueid FROM timetables where ttname = Always', sqlState: '42S22', sqlMessage: "Unknown column 'Always' in 'where clause'" }
解决方案
核心问题是字符串类型的查询参数未添加引号,MySQL将Always识别为列名而非字符串值。推荐使用参数化查询解决,同时避免SQL注入风险。
方法1:参数化查询(最佳实践)
修改singledbentry函数支持参数传入,调用时传递参数即可自动处理引号:
async function singledbentry(sql, params = []) { const [stripDbInfoLayer] = await pool.query(sql, params) return stripDbInfoLayer[0] } async function activetime(inputusercode) { // 第一个查询使用参数化 let codetimetable = await singledbentry('SELECT usertimetable FROM users where usercode = ?', [inputusercode]); console.log(codetimetable); console.log(codetimetable.usertimetable); // 第二个查询使用参数化 let timetabledata = await singledbentry('SELECT ttday, ttfrom, tttill, ttuniqueid FROM timetables where ttname = ?', [codetimetable.usertimetable]); console.log(timetabledata); } activetime('4310')
参数化查询会自动处理字符串的引号包裹,同时能有效防御SQL注入攻击,是数据库操作的标准规范。
方法2:手动拼接引号(不推荐)
若暂时不愿修改为参数化查询,可手动给变量添加单引号,但需转义变量中的特殊字符(如单引号):
var sql = `SELECT ttday, ttfrom, tttill, ttuniqueid FROM timetables where ttname = '${codetimetable.usertimetable.replace(/'/g, "\\'")}'`;
此方法存在SQL注入风险,例如当变量值为' OR 1=1 --时,会导致查询返回所有数据,因此不建议使用。
内容的提问来源于stack exchange,提问作者IoT-Practitioner
相关产品推荐
相关产品推荐

