你如何在python中将sql的输出写入csv文件

use*_*980 3 python

我正在尝试连接到oracle表并执行sql.我需要将结果集导出到csv文件.我的代码如下:

import pyodbc
import csv

cnxn = pyodbc.connect("DSN=11g;UID=test101;PWD=passwd")
cursor = cnxn.cursor()
cursor.execute(sql)
row = cursor.fetchall()
with open('data.csv', 'w', newline='') as fp:
    a = csv.writer(fp, delimiter=',')
    for line in row:
        a.writerows(line)

cursor.close()
Run Code Online (Sandbox Code Playgroud)

当我在for循环中打印到行时,我得到这样的东西:

('Production', 'farm1', 'dc1prb01', 'web')
('Production', 'farv2', 'dc2pr2db01', 'app.3')
('Production', 'farm5', 'dc2pr2db02', 'db.3')
Run Code Online (Sandbox Code Playgroud)

这不起作用.我可能会缺少什么想法?

Pad*_*ham 6

这将是一行的写作:

 a.writerow(line)
Run Code Online (Sandbox Code Playgroud)

writerows 期望迭代的迭代次数,因此它将遍历分别编写每个char的子字符串.

如果你想使用writer在行上调用它:

    row = cursor.fetchall()
    with open('data.csv', 'w', newline='') as fp:
            a = csv.writer(fp, delimiter=',')
            a.writerows(row)
Run Code Online (Sandbox Code Playgroud)

如果你使用python2 remove newline='',换行符是*python*3关键字:

  row = cursor.fetchall()
    with open('data.csv', 'w') as fp:
            a = csv.writer(fp, delimiter=',')
            a.writerows(row)
Run Code Online (Sandbox Code Playgroud)