簡體   English   中英

將SQL輸出存儲到變量並調用變量

[英]Storing SQL output to variable and calling the variable

我試圖從SQL查詢中獲取輸出,並將其寫入變量。 這是使用Redshift DB

cur.execute(sql.SQL("""select prod_name,prod_category,count(*) from sales limit 5""")
sql_output = cur.fetchall()

上面提取了5條記錄並將其存儲到sql_output。 現在,我嘗試將其寫入PowerPoint幻燈片中的表格,如下所示:

name_1 = sql_output[0][0]
category_1 = sql_output[0][1]
count_1 = sql_output[0][3]
name_2 = sql_output[1][0]
category_2 = sql_output[1][1]
count_2 = sql_output[1][3]
name_3 = sql_output[2][0]
category_3 = sql_output[2][1]
count_3 = sql_output[2][3]
name_4 = sql_output[3][0]
category_4 = sql_output[3][1]
count_4 = sql_output[3][3]
name_5 = sql_output[4][0]
category_5 = sql_output[4][1]
count_5 = sql_output[4][3]

if len(sql_output) = []:
    table.cell(1, 0).text = str('NA')
    table.cell(1, 1).text = str('NA')
    table.cell(1, 2).text = str('NA')
elif:
    table.cell(1, 0).text = name_1
    table.cell(1, 1).text = str(category_1)
    table.cell(1, 2).text = str(count_1)
    table.cell(2, 0).text = name_2
    table.cell(2, 1).text = str(category_2)
    table.cell(2, 2).text = str(count_2)
    table.cell(3, 0).text = name_3
    table.cell(3, 1).text = str(category_3)
    table.cell(3, 2).text = str(count_3)
    table.cell(4, 0).text = name_4
    table.cell(4, 1).text = str(category_4)
    table.cell(4, 2).text = str(count_4)
    table.cell(5, 0).text = name_5
    table.cell(5, 1).text = str(category_5)
    table.cell(5, 2).text = str(count_5)

下面的工作正常,但是輸出為null,則上面的操作失敗並出現錯誤:

IndexError: list index out of range

嘗試這個

for index, row in enumerate(sql_output):
    table.cell(index+1, 0).text = row[0]
    table.cell(index+1, 1).text = str(row[1])
    table.cell(index+1, 2).text = str(row[3])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM