【问题标题】:Storing SQL output to variable and calling the variable将 SQL 输出存储到变量并调用变量
【发布时间】:2019-01-28 06:43:02
【问题描述】:

我正在尝试从 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

【问题讨论】:

  • 你想要什么?为什么不使用 for 循环?我看到你的代码重复了很多次
  • @ChienNguyen,我也尝试了如我最初的帖子中所示的循环(帖子已编辑),但我不断得到索引超出范围错误.. 我想知道我怎么能运行这个无论 SQL 返回的记录数如何,都不会出现任何错误。

标签: python python-3.x amazon-redshift


【解决方案1】:

试试这个

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-12
    • 1970-01-01
    • 1970-01-01
    • 2022-01-09
    • 2018-01-27
    • 2023-02-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多