在where子句中的Javascript SQL请求Bad Field Error

时间:2014-10-10 10:29:44

标签: javascript sql node.js

只有当同一封电子邮件没有得分大于当前分数时,才会更新分数,而是显示错误:

Error: Error: ER_BAD_FIELD_ERROR: Unknown column 'li' in 'where clause'
function postScores(useremail, username, scoreValue, leaderboardName) {
    if (leaderboardName === "GHOSTS" || leaderboardName === "PACMAN" || leaderboardName === "OVERALL") {
        connection.query('UPDATE SCORES_' + leaderboardName + ' SET SCORES=' + scoreValue + ' WHERE SCORES < ' + scoreValue + ' AND USER_EMAIL=' + useremail,
            function(err, rows, fields) {
                if (err) {
                    console.log("Failed to Update. Attempting to Insert.");
                    console.log("Error: " + err);
                    connection.query(
                        'INSERT INTO SCORES_' + leaderboardName + '(USER_EMAIL, USER_NAME, SCORES) VALUES (?,?,?)', [
                            useremail, username, scoreValue
                        ],
                        function(err, rows, fields) {
                            if (err) {
                                console.log("Total Failure. Systems down");
                            } else {
                                console.log("Success. Inserted new Scores");
                            }
                        });
                }
            });
    } else {
        // Reference to Non-Existent Leaderboard
        return console.log('Specified Leaderboard of the name ' + leaderboardName + ' does not Exist');
    }
}

1 个答案:

答案 0 :(得分:4)

在UPDATE查询中,不要将原始数据连接到值中,使用占位符并为值传递数组,方法与INSERT查询相同。

未加引号的字符串值可能导致SQL语法错误。通过使用占位符,您不需要处理值中的引号。

connection.query('UPDATE SCORES_' + leaderboardName + ' SET SCORES = ? WHERE SCORES < ? AND USER_EMAIL = ?',
    [scoreValue, scoreValue, useremail],
    function (err, rows, fields) {