Passing parameters to a query

Passing parameters to a query

Using values in a query condition, for example, or in a HAVING statement can be done “inline”, by integrating the value in the query string itself:

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

or it can be done by extracting the values in a separate list of parameters and using question mark placeholders (?) in the query string:

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

The recommended way of passing values to a query is with question mark placeholders, to avoid any attempts of hacking or SQL injection.