向查询传递参数编辑

例如,在查询条件或 HAVING 语句中使用值可以通过将值直接集成到查询字符串中来完成

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
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"
}

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

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
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 注入尝试。