请帮我简化一下。我的程序有很多字段存储在数据库中(每个表大约100个),我认为这不是一个好主意。
这是我的代码
eacode = req.body.eacode;
hcn = req.body.hcn;
shsn = req.body.shsn;
name = req.body.name;
TENURHWS = req.body.TENURHWS;
TENURLOT = req.body.TENURLOT;
DWELTYPE = req.body.DWELTYPE;
DWELTYPE_OTH = req.body.DWELTYPE_OTH;
ROOF = req.body.ROOF;
ROOF_OTH = req.body.ROOF_OTH;
WALL = req.body.WALL;
WALL_OTH = req.body.WALL_OTH;
FLOOR = req.body.FLOOR;
BEDROOM = req.body.BEDROOM;
db.run("INSERT INTO form12(name,TENURHWS,TENURLOT,DWELTYPE,DWELTYPE_OTH,ROOF,ROOF_OTH,WALL,WALL_OTH,FLOOR,BEDROOM) VALUES $name,$TENURHWS,$TENURLOT,$DWELTYPE,$DWELTYPE_OTH,$ROOF,$ROOF_OTH,$WALL,$WALL_OTH,$FLOOR,$BEDROOM)",
{
$name : name,
$TENURHWS : TENURHWS,
$TENURLOT : TENURLOT,
$DWELTYPE : DWELTYPE,
$DWELTYPE_OTH : DWELTYPE_OTH,
$ROOF : ROOF,
$ROOF_OTH : ROOF_OTH,
$WALL : WALL,
$WALL_OTH : WALL_OTH,
$FLOOR : FLOOR,
$BEDROOM : BEDROOM
});
答案 0 :(得分:0)
如果您的代码太长而无法手动输入每个部分,请查看是否可以使用循环来获得类似的结果。在您的示例中,如果req.body
仅包含应保存到数据库的密钥,则可以使用以下代码:
var fieldNames = req.body.keys();
// You could also store a manually maintained list of fields in you own list.
// var fieldNames = ["field1", "field2", "field3", ... , "fieldn"];
sqlStatement = "INSERT INTO form12(" + fieldNames.join(",") + ") Values (";
for(var i = 0; i < fieldNames.length; i++) {
// Add other logic for building the values part
sqlStatement += "'" + req.body[fieldNames[i]] + "', ";
}
// Remove trailing comma
sqlStatement += ")";