我对sql的了解不多,正在从事我的第一个项目
了解到有关更新查询的信息首先,我创建了一个如下所示的辅助函数
const updateFieldInTable = (tableName, conditionParameter, updatedCondition, locationReference, locationReferenceValue) => {
return new Promise((resolve, reject) => {
pool.getConnection((error, connection) => {
if (error) return reject(error)
const query = `UPDATE ${tableName} SET ${conditionParameter} = ${updatedCondition} WHERE ${locationReference} = ${locationReferenceValue}`
connection.query(query, (error, response) => {
connection.destroy()
if (error) return reject(error)
return resolve(response)
})
})
})
}
我正在使用它来更新表中的字段,因此我创建了一条虚拟路由来为我执行此任务并查看其是否有效
app.get('/test', async (req, res) => {
const resultFromQuery = await updateFieldInTable('personal', 'gradYear', 2017, 'userId', 1234)
console.log(`Result from Query:`, resultFromQuery)
res.status(200).json(resultFromQuery[0])
});
上面的查询工作正常,但是如果我将其更改为varchar,则会收到以下错误
错误:ER_BAD_FIELD_ERROR:“字段列表”中的未知列“ ryan”
这是给我错误的原因
app.get('/test', async (req, res) => {
const resultFromQuery = await updateFieldInTable('personal', 'school', 'ryan', 'userId', 1234)
console.log(`Result from Query:`, resultFromQuery)
res.status(200).json(resultFromQuery[0])
});
这就是我的sql哑巴样子
`gradYear` int(4) DEFAULT NULL,
`gradMonth` enum('january','february','march','april','may','june','july','august','september','october','november','december') CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL,
`school` varchar(255) DEFAULT NULL,
`degree` varchar(255) DEFAULT NULL,
答案 0 :(得分:1)
当您要在db上插入/更新字符串值时,它应该在单引号之间。与您的参数SQL似乎
SET school = ryan
但这应该是
SET school = 'ryan'
。
因此将ryan值发送给您的函数,例如
'\'ryan\''
或"'ryan'"