简体   繁体   English

如何使用Jupyter Notebooks Python将变量传递到SQL查询

[英]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. 这是显示Python变量替换的完整示例。 https://colab.research.google.com/notebook#fileId=0B7I8C_4vGdF6Mk1RMm1Fdm9EQVU https://colab.research.google.com/notebook#fileId=0B7I8C_4vGdF6Mk1RMm1Fdm9EQVU

The notebook shows the following: 笔记本显示以下内容:

  1. Create a BigQuery table from some random CSV data. 根据一些随机CSV数据创建一个BigQuery表。
  2. Query that table using the Pandas GBQ connector. 使用Pandas GBQ连接器查询该表。
  3. Construct and execute a query against that table using Python variable substitution. 使用Python变量替换构造并执行对该表的查询。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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