Сохранение вывода SQL в переменную и вызов переменной - PullRequest
0 голосов
/ 28 января 2019

Я пытаюсь получить вывод из запроса 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)

Ниже работает просто отлично, но если вывод равен нулю, вышеприведенный сбой и выдает ошибку:

IndexError: list index out of range

1 Ответ

0 голосов
/ 28 января 2019

Попробуйте это

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])
...