[英]How can I use a variable as column name in mysql / express?
目前我有這個問題,問題是表名有一組引號(它是一個字符串),這會使服務器崩潰。
const update = 'the name of my column';
const UpdateQuery = `UPDATE scores
SET ${mysql.escape(update)} = ${mysql.escape(newValue)}
WHERE score_id = ${mysql.escape(singleScore.score_id)}`;
mysql.escape()
適用於除列名以外的所有內容。
如果我在注入變量后對查詢進行 console.log,這就是我得到的結果:
UPDATE scores
SET 'the name of my column' = 1
WHERE score_id = 1
看起來您正在使用mysql NPM 包。
escape
方法用於轉義查詢值。 要轉義查詢標識符(如列名),您應該改用escapeId
方法。 您的代碼應如下所示:
const update = 'the name of my column';
const UpdateQuery = `UPDATE scores
SET ${mysql.escapeId(update)} = ${mysql.escape(newValue)}
WHERE score_id = ${mysql.escape(singleScore.score_id)}`;
同樣,如果您使用替換,請使用雙問號而不是單問號來轉義標識符。
const update = 'the name of my column';
const UpdateQuery = `UPDATE scores
SET ?? = ?
WHERE score_id = ?`;
const replacements = [update, newValue, singleScore.score_id];
只需稍加改動的泰米爾瓦南解決方案即可解決此問題
db.query(
'UPDATE scores SET '+update+' = ? Where score_id = ?',
[newValue, singleScore.score_id],
(err, result) => {
if (err) throw err;
console.log(`Changed ${result.changedRows} row(s)`);
}
);
對於奇怪的 MySQL 列名,您不能在它們周圍加上單引號。 單引號只是將值轉換為字符串。
反引號在 MySQL 中用於此目的。 例如
UPDATE `table with space` SET `column with space` = 'bar';
檢查下面的代碼。 它可能有效,
con.query(
'UPDATE scores SET '+update+' = ? Where score_id = ?',
// Old - [${mysql.escape(newValue)}, ${mysql.escape(singleScore.score_id)}],
/* Update - */ [newValue,singleScore.score_id],
(err, result) => {
if (err) throw err;
console.log(`Changed ${result.changedRows} row(s)`);
}
);
根據您的查詢, ${mysql.escape(update)}
包含值的單引號。
所以,昨天我自己也遇到了這個問題。 我通過不小心搜索變量表名找到了解決方案。
解決方案是這樣查詢:
const columnName = 'the name of my column';
query("UPDATE `scores` SET ?? = ? WHERE `score_id` = ?;", [columnName, singleScore.score_id, newValue]);
讓我知道這是否適合你
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.