PYODBC Fetchmany到csv只输出标题

时间:2017-01-12 23:50:05

标签: python pyodbc

我尝试使用csv使用pyodbcfetchmany()写一个大表。我可以正确连接,但唯一写入的记录是标题。循环db游标的正确方法是什么?

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.

2 个答案:

答案 0 :(得分:1)

我会保持简单并且只是迭代:

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(),那么它应该很容易修改。

答案 1 :(得分:1)

测试表明,至少部分问题源于与file关联的csv.writer对象的处理。使用上下文管理器(with块)来显式处理file似乎已经解决了我的问题:

with open('file.csv', 'w', encoding ='UTF-8', newline='\n') as csvfile:
    c = csv.writer(csvfile, 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)