SQL查询输出到.csv

时间:2017-11-04 05:22:38

标签: python api csv export-to-csv

我正在从python API运行SQL查询,并希望收集结构化数据(其标题下的列式数据).CSV格式。

到目前为止,这是我的代码。

sql = "SELECT id,author From researches WHERE id < 20 " 
cursor.execute(sql)
data = cursor.fetchall()
print (data)
with open('metadata.csv', 'w', newline='') as f_handle:
    writer = csv.writer(f_handle)
    header = ['id', 'author']
    writer.writerow(header)
    for row in data:
        writer.writerow(row)

现在数据正在控制台上打印但没有进入.CSV文件这就是我得到的output

我错过了什么?

3 个答案:

答案 0 :(得分:0)

以下是您尝试执行的操作的简单示例:

import sqlite3 as db
import csv

# Run your query, the result is stored as `data`
with db.connect('vehicles.db') as conn:
    cur = conn.cursor()
    sql = "SELECT make, style, color, plate FROM vehicle_vehicle"
    cur.execute(sql)
    data = cur.fetchall()

# Create the csv file
with open('vehicle.csv', 'w', newline='') as f_handle:
    writer = csv.writer(f_handle)
    # Add the header/column names
    header = ['make', 'style', 'color', 'plate']
    writer.writerow(header)
    # Iterate over `data`  and  write to the csv file
    for row in data:
        writer.writerow(row)

答案 1 :(得分:0)

import pandas as pd

import numpy as np

from sqlalchemy import create_engine

from urllib.parse import quote_plus

params = quote_plus(r'Driver={SQL Server};Server=server_name;                        Database=DB_name;Trusted_Connection=yes;')

engine = create_engine("mssql+pyodbc:///?odbc_connect=%s" % params)

sql_string = '''SELECT id,author From researches WHERE id < 20 '''

final_data_fetch = pd.read_sql_query(sql_string, engine)

final_data_fetch.to_csv('file_name.csv')

希望这会有所帮助!

答案 2 :(得分:0)

您可以将所有结果转储到 csv 文件而无需循环:

data = cursor.fetchall()
...
writer.writerows(data)