我尝试使用csv
使用pyodbc
向fetchmany()
写一个大表。我可以正确连接,但唯一写入的记录是标题。循环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.
答案 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)