1

我正在开发一个小型移动网络应用程序。我有一个包含LIKE子句的查询。例如:

SELECT from posts WHERE (title LIKE '%car%') or (content LIKE '%car%');

我遇到的问题是 javascript 中的变量在它们的值周围有单引号。所以我得到以下信息:

SELECT from posts WHERE (title LIKE '%'car'%') or (content LIKE '%'car'%');

我正在以这种方式构建的实际字符串:

"SELECT from posts WHERE (title LIKE '%" + client.escape(input) + "%') or (content LIKE '%" + client.escape(input) + "%');"
4

1 回答 1

1

封闭'的 s 由转义函数自动添加,因此将%s 移动到变量内部并将其转义,然后'从查询中删除 s:

input = client.escape('%' + input + '%'); //=== "'%escaped_input%'"
client.query("SELECT * FROM posts WHERE (title LIKE " + input + ") or (content LIKE " + input + ")", function(err, results) {
     // ...
});

参考 - 转义查询值

或者,您也应该能够使用模拟的预处理语句语法:

input = '%' + input + '%';
client.query("SELECT * FROM posts WHERE (title LIKE ?) or (content LIKE ?)", [input, input], function(err, results) {
     // ...
});

This will perform something similar to sprintf, replacing the ? placeholders by the properly escaped items (internally using the same escape method as above) from second argument array, in the order they were passed - the placeholders' order corresponds to the array items' order.


Side-note: I assume you've oversimplified the query removing all the fields from SELECT statement, remember to select at least a field or all of them (*) otherwise it is not valid SQL syntax.

于 2013-05-08T02:10:39.373 回答