我正在使用节点js和用于连接到postrgresql的模块pg i想要搜索标签数据库,但我无法使其工作,在变量标签中的我保存了url的参数,但咨询不会返回任何结果。 我该如何解决?
I am using node js and the module pg for connect to postrgresql i want to make a search for a database of tags but i can't make it work, in the variable tag i saved the param of the url , but the consult doesn't return any results. how can i fix?
app.get("/tags", function(req, res){ var tag = req.query.q; res.json(tag) var search = db.client.query("SELECT * FROM tags WHERE name LIKE '%$1%'", [tag], function(err, result){ res.json(result); } ); });推荐答案
我不知道node.js PostgreSQL接口很好,但我认为我可以看到问题所在。这是一个SQL字符串文字,其中包含带编号的占位符:
I don't know the node.js PostgreSQL interface that well but I think I can see the problem. This is an SQL string literal that contains a numbered placeholder:
'%$1%'该字符串中的 $ 1 不会替换为 tag 因为字符串中的占位符根本不是占位符,它们只是恰好具有与占位符相同形式的子字符串。
The $1 inside that string won't be replaced with the value of tag because placeholders inside strings are not placeholders at all, they're just substrings that happen to have the same form as a placeholder.
两个常用选项是:
第一个看起来像这样:
db.client.query("SELECT * FROM tags WHERE name LIKE $1", ['%' + tag + '%'], ...,第二个是这样的:
db.client.query("SELECT * FROM tags WHERE name LIKE '%' || $1 || '%'", [tag], ...使用您所使用的任何一种方法喜欢。
Use whichever approach you prefer.
更多推荐
如何在PostgreSQL和Node JS中进行类似搜索
发布评论