【问题标题】:PYTHON 3.7 - export the result of a query DB to a CSV filePYTHON 3.7 - 将查询数据库的结果导出到 CSV 文件
【发布时间】:2019-06-07 01:50:33
【问题描述】:

我最近开始使用 python,我正在尝试将查询结果导出到 csv 文件,但没有成功。

id = 563;

try:
    cursor.execute("SELECT start_time,end_time FROM appointment WHERE box_id=%s", (id,))
    data = cursor.fetchall()

    with open('dataTester.csv', 'w') as fp:
        a= csv.writer(fp, delimiter=',')
        for line in data:
           a.writerows(line)

    for row in data:
        print (row[0],row[1])
    cursor.close()
    connection.close()
except:
    print ("error")

connection.close()

我有以下错误:

预期可迭代,而不是 datetime.datetime

错误出现在以下行:a.writerows(line)

【问题讨论】:

  • 在错误所在行之前添加一个print(type(line), line),在data = cursor.fetchall() 之后添加一个print(data)。你认为你从查询中得到的似乎并不是你认为你得到的。

标签: python python-3.x database export-to-csv


【解决方案1】:

您没有指定结果元组的索引元素。尝试更多类似的方法:

a.writerows(line[0], line[1])

【讨论】:

    猜你喜欢
    • 2015-01-10
    • 1970-01-01
    • 2023-04-04
    • 2017-12-31
    • 1970-01-01
    • 1970-01-01
    • 2018-02-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多