Javascript:使用动态列名执行SQL查询

时间:2019-03-22 18:47:21

标签: javascript mysql sql

我有4个资源,并且可以减少这些资源,但是每次减少资源时,我的函数都会检查资源值是否降至0以下。如果确实如此,那么它将调用我的setColumnToZero函数,该函数会将列值设置为0。我的问题是,当我尝试动态更新列时,我的函数将不起作用(1个函数占用4个资源。)如果我手动更新列名,我的代码将起作用,但是如何使它动态地起作用

edit:因此,如果我手动键入Crop_Inventory而不是?在我的查询中,它有效

removeCropFromInventory: function(cropAmount){
    return new Promise(function(resolve,reject){
        let sql = "UPDATE resources SET Crop_Inventory = Crop_Inventory - (?) WHERE resources_FK_PlayerId = (?) AND resources_FK_GameId = (?)";
        var value = [cropAmount, global.id, global.gameId];
        db.query(sql, value, function(err,result,fields){
            if(err){
                console.log(err);
            } else{
                crop_inventory = crop_inventory - cropAmount;
                if(crop_inventory < 0){
                    module.exports.setColumnToZero('Crop_Inventory').then(function(crop_inventory){
                        resolve(crop_inventory);
                    });
                } else{
                    resolve(crop_inventory);
                }
            }
        });
    });
}


setColumnToZero: function(Column){
    return new Promise(function(resolve,reject){
        let sql = "UPDATE resources SET (?) = 0 WHERE resources_FK_PlayerId = (?) AND resources_FK_GameId = (?)"; //This is where error occurs
        var value = [Column, global.id, global.gameId];
        db.query(sql, value, function(err,result,fields){
            if(err){
                console.log(err);
            } else{
                crop_inventory = 0
                resolve(crop_inventory);
            }
        });
    }); 
}

0 个答案:

没有答案