简体   繁体   中英

How to pass variables into SQL query using Jupyter Notebooks Python

For Example:

%bq query -n qu

SELECT 

    *

FROM

    Table

WHERE 

    [passed in variable (column)] = true

Then i want to execute the query in a loop

for row in data:

  bq.execute qu(row[1])

Does something along these lines exist?

EDIT: I figured out a solution for anyone who comes across this question

For row in [dataset with your variables]:

   query = "SELECT * FROM DATASET WHERE {} = TRUE".format(variableData[0])

   tab = bq.Query(query)

   df = tab.execute(output_options=bq.QueryOutput.dataframe()).result()

   qu = [list(x) for x in df.as_matrix()]

   print(qu)

Here's a complete example showing Python variable substitution. https://colab.research.google.com/notebook#fileId=0B7I8C_4vGdF6Mk1RMm1Fdm9EQVU

The notebook shows the following:

  1. Create a BigQuery table from some random CSV data.
  2. Query that table using the Pandas GBQ connector.
  3. Construct and execute a query against that table using Python variable substitution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM