python - PYODBC Fetchmany 到 csv 仅输出 header

标签 python pyodbc

我正在尝试使用fetchmany()使用pyodbc将一个大表写入csv。我可以正确连接,但唯一写入的记录是 header 。循环数据库游标的正确方法是什么?

cxn = pyodbc.connect(cxn data)

mssql_cursor = cxn.cursor()
mssql_cursor.execute(sql_query)

c = csv.writer(open('file.csv', 'w', encoding ='UTF-8', newline='\n'), delimiter='|')
c.writerow([i[0] for i in mssql_cursor.description])
results = mssql_cursor.fetchmany(10000)
while results:
    c.writerows(results)
    results = mssql_cursor.fetchmany(10000)

mssql_cursor.close()
cxn.close()

编辑:看起来通过 fetchmany 方法没有返回任何内容。我添加了 print(len(results)),结果为 0。

最佳答案

我会保持简单并进行迭代:

cxn = pyodbc.connect(cxn data)

mssql_cursor = cxn.cursor()
rows = mssql_cursor.execute(sql_query)

with open('file.csv', 'w', encoding ='UTF-8', newline='\n') as csvfile:
    c = csv.writer(csvfile, delimeter='|')

    for row in rows:
        c.writerow(row)

mssql_cursor.close()
cxn.close()

这有效吗?如果它在这里工作并且您想切换到 executemany(),那么修改它应该相当容易。

关于python - PYODBC Fetchmany 到 csv 仅输出 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41625114/

相关文章:

python - python中的计算器问题

python - 出现错误“赋值前引用局部变量 - 如何修复?

python - OpenCV:AttributeError:模块 'cv2' 没有属性 'face'

python - Pyodbc - 打印前 10 行(python)

python - 使用 python 连接 SQL Server 时遇到问题

python - 在 Django ORM 之外编辑数据库

python - 如何比较hdfs文件和unix文件?

python - 使用 Python 连接到 MS Access

sql-server - freetds 和 pyodbc 无法连接

Python - 使用 pyodbc 使用来自 Excel 数据连接的信息连接到远程服务器