将数据单行输出到csv文件

时间:2018-11-15 10:00:34

标签: python-3.x cx-oracle

如何将数据库中的数据单行输出到csv文件?现在看起来像这样:

ID
SN
CLASS_ID 

我需要为:

ID SN CLASS_ID

到目前为止,我的代码:

path = "C:\IBSO\DOK\exercise_1.csv"
try:
    connection = cx_Oracle.connect("admin", "123", "localhost")
except cx_Oracle.DatabaseError as err:
    print("Error auth", err)
cursor = connection.cursor()
cursor.execute("""
    SELECT * FROM Z#PRODUCT
    WHERE ROWNUM <=10
    """)
with open(path, 'w', newline='') as csvfile:
     writer = csv.writer(csvfile, delimiter=' ')
     for column in cursor.description:
        writer.writerow(''.join(column[0]))

2 个答案:

答案 0 :(得分:0)

您可以使用pandas.read_sql(conn, query)将SQL读入pandas.DataFrame,然后使用pandas.to_csv(path)保存到文件

因此代码将类似于:

import pandas as pd 
path = "C:\IBSO\DOK\exercise_1.csv"
try:
    connection = cx_Oracle.connect("admin", "123", "localhost")
except cx_Oracle.DatabaseError as err:
    print("Error auth", err)
query = """
        SELECT * FROM Z#PRODUCT
        WHERE ROWNUM <=10
        """
df = pd.read_sql(connection, query)
df.to_csv(path, index= False)

从理论上讲,您可以将其单行插入:pd.read_sql(connection, query).to_csv(path, index= False),但我尚未对此进行测试。

答案 1 :(得分:0)

问题出在

for column in cursor.description:
    writer.writerow(''.join(column[0]))

我假设每个column是一个字符串,因此对于每个column,您将用空字符串写出列名中各个字符的连接结果,例如:

In [58]: ''.join('asdfe')                                                                 
Out[58]: 'asdfe'

并使用writerow,然后在单个行上放置一个列名。

您想要做的是将工作留在writerow上,该工作旨在将CSV(不正确地说)中包含的值放入CSV中:

with open(path, 'w', newline='') as csvfile:
     writer = csv.writer(csvfile, delimiter=' ')

     writer.writerow(cursor.description)
     # other code where you process and output the query results