我有一个 javascript 函数需要返回产品列表。它使用 postgres 来检索产品列表。该函数传递一个categoryId
和一个可选的typeId
。所以我需要基于这些构建一个 SQL 查询。
当然我可以做这样的事情:
async function getProducts(categoryId, typeId = false) {
let products;
if (typeId) {
products = await sql`select * from products where categoryId=${categoryId} and typeId=${typeId}`
}
else {
products = await sql`select * from products where categoryId=${categoryId}`
}
return products;
}
但是我怎样才能用模板文字语法动态地“构建”SQL 查询呢?
像这样的事情:
async function getProducts(categoryId, typeId = false) {
let query = `select * from products where categoryId=${categoryId}`;
if (typeId) {
query += ` AND typeId=${typeId}`;
}
products = await sql`${query}` // doesn't work, so how could I generate a dynamic query like this?
return products;
}
(注意:这是使用@vercel/postgres)
Vercel 没有记录这一点,但他们的@vercel/postgres https://github.com/vercel/storage/tree/main/packages/postgres包装只是一个紧密的包装@neondatabase/无服务器所以你可以使用他们的方法 https://github.com/neondatabase/serverless#pool-and-client以及。这sql`…`
, pool.sql`…`
and client.sql`…`
模板标签不能以任何其他方式使用,它们在不与模板字符串一起使用时将引发异常。但是,您可以使用.query()
方法将查询测试和参数值作为单独的参数:
async function getProducts(categoryId, typeId) {
let query = `select * from products where categoryId=$1`;
let params = [categoryId];
if (typeId != null) {
query += ` AND typeId=$2`;
params.push(typeId);
}
const products = await sql.query(query, params);
return products;
}
当然,手动构建 SQL 字符串是有风险的 - 它很容易导致软件中出现语法错误和 SQL 注入安全漏洞。确保always使用参数化查询,切勿将动态值插入查询中。
对于常见用例(例如具有各种字段的动态条件),请考虑使用 ORM 或查询构建器库,它们配备了针对这些事情的经过尝试和测试的辅助函数。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)