使用switch语句获取函数

时间:2018-03-21 18:15:35

标签: javascript express

尝试获取正确的sql语句,但它不起作用:

function getsql (key) {
    switch (key) {
        case 1:
            return 'SELECT * FROM main WHERE 1';
            break;
        case 2:
            return 'SELECT * FROM location WHERE 1';
            break;
        default:
            break;
    }
};

operations.get('/filter/:key', function (req, res) {
    var sql = getsql(parseInt(req.params.key));
    db.query(sql, function (error, results) {
        res.json(results);
    })
})

我不知道该怎么做,请帮助我。

1 个答案:

答案 0 :(得分:0)

您的key是一个字符串,将其转换为Int。 parseInt(key, 10)

function getSQL(key) {
    switch (key) {
        case 1:
            return `SELECT * FROM main WHERE 1`;
        case 2:
            return `SELECT * FROM location WHERE 1`;
        default:
            return ``;
    }
}

router.get(`/filter/:key`, (req, res) => {
    const key = parseInt(req.params.key, 10);
    const sql = getSQL(key);
    res.send(`The SQL text: ${sql}`);
});

Working demo