[英]Python code to execute a SQL script and create a CSV file with a customised name
我在 excel 中存儲了雪花 SQL 查詢列表。附上示例格式,但原始 excel 有 50 多行。
我已經編寫了一個 python 代碼來讀取和執行這些查詢,但 output 並不像我預期的那樣。 這里的目的是讀取excel並執行'query'列的查詢,並將查詢結果保存在CSV中,文件名是88795099932388'Scenario'列中提到的文件名。
我編寫的 python 代碼在 output 路徑中執行並創建了不同的文件,但所有 CSV 文件都具有上次查詢的結果,即 customer_count.csv 文件也具有與 customer_attribute.csv 相同的數據
如果我的 excel 有 50 個不同的場景,它會創建 50 個不同的 CSV 文件,但所有這些文件中的數據都是第 50 次查詢的結果
下面是我的代碼,我不確定哪里出了問題。 有人可以幫我嗎
from EXCEL_CONNECTION import *
from SNOWFLAKE_CONNECTION import *
import pandas
import openpyxl
wb = openpyxl.load_workbook("QUERY.xlsx")
ws = wb.get_sheet_by_name('Sheet1')
cur = ctx.cursor()
for col in ws.iter_rows(min_row=2, min_col=2, max_col=2):
for cell2 in col:
df1 = (cell2.value)
for row in ws.iter_rows(min_row=2, min_col=3, max_col=3):
for cell in row:
cur.execute(cell.value)
df = cur.fetch_pandas_all()
df.to_csv(r"target path" + df1 + r".csv")
我無法用眼睛發現問題。 所以我會做下一個最好的事情......添加一些調試並查看實際發生的事情:
for col in ws.iter_rows(min_row=2, min_col=2, max_col=2):
print('col', col)
for cell2 in col:
print('cell2', cell2.value)
df1 = (cell2.value)
for row in ws.iter_rows(min_row=2, min_col=3, max_col=3):
print('row', row)
for cell in row:
print('cell', cell.value)
cur.execute(cell.value)
df = cur.fetch_pandas_all()
print('to_csv', r"target path" + df1 + r".csv")
df.to_csv(r"target path" + df1 + r".csv")
我很困惑為什么你將文件名放入元組(cell2.value)
而不是直接使用它。 SQL這個cell
是直接用的?
但是你會看到你用不同的文件名執行了 N execute
,然后它將是“結果實際上不同嗎”或者你看到當你在循環 X 時你沒有跨過 Y,或者你正在做每一個X 代表每個 Y(這聽起來像您得到的 output)。
當您確切知道發生了什么時,您可以提出更有針對性的問題。 簡化的回購協議,如:
from EXCEL_CONNECTION import *
from SNOWFLAKE_CONNECTION import *
cur = ctx.cursor()
cur.execute('select count(*) from customer')
df = cur.fetch_pandas_all()
df.to_csv(r"target path\customer_count.csv")
cur.execute('select * from customer')
df = cur.fetch_pandas_all()
df.to_csv(r"target path\customer_attribute.csv")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.