将参数传递给查询

编辑

在查询条件中使用值,例如,或者在 HAVING 语句中,可以通过“内联”方式完成,即将值集成到查询字符串本身中

resp = client.sql.query(
    format="txt",
    query="SELECT YEAR(release_date) AS year FROM library WHERE page_count > 300 AND author = 'Frank Herbert' GROUP BY year HAVING COUNT(*) > 0",
)
print(resp)
response = client.sql.query(
  format: 'txt',
  body: {
    query: "SELECT YEAR(release_date) AS year FROM library WHERE page_count > 300 AND author = 'Frank Herbert' GROUP BY year HAVING COUNT(*) > 0"
  }
)
puts response
const response = await client.sql.query({
  format: "txt",
  query:
    "SELECT YEAR(release_date) AS year FROM library WHERE page_count > 300 AND author = 'Frank Herbert' GROUP BY year HAVING COUNT(*) > 0",
});
console.log(response);
POST /_sql?format=txt
{
	"query": "SELECT YEAR(release_date) AS year FROM library WHERE page_count > 300 AND author = 'Frank Herbert' GROUP BY year HAVING COUNT(*) > 0"
}

或者可以通过将值提取到单独的参数列表中,并在查询字符串中使用问号占位符 (?) 来完成

resp = client.sql.query(
    format="txt",
    query="SELECT YEAR(release_date) AS year FROM library WHERE page_count > ? AND author = ? GROUP BY year HAVING COUNT(*) > ?",
    params=[
        300,
        "Frank Herbert",
        0
    ],
)
print(resp)
response = client.sql.query(
  format: 'txt',
  body: {
    query: 'SELECT YEAR(release_date) AS year FROM library WHERE page_count > ? AND author = ? GROUP BY year HAVING COUNT(*) > ?',
    params: [
      300,
      'Frank Herbert',
      0
    ]
  }
)
puts response
const response = await client.sql.query({
  format: "txt",
  query:
    "SELECT YEAR(release_date) AS year FROM library WHERE page_count > ? AND author = ? GROUP BY year HAVING COUNT(*) > ?",
  params: [300, "Frank Herbert", 0],
});
console.log(response);
POST /_sql?format=txt
{
	"query": "SELECT YEAR(release_date) AS year FROM library WHERE page_count > ? AND author = ? GROUP BY year HAVING COUNT(*) > ?",
	"params": [300, "Frank Herbert", 0]
}

推荐的向查询传递值的方式是使用问号占位符,以避免任何黑客攻击或 SQL 注入的尝试。