数据库
首页 > 数据库> > python – SQL查询输出到.csv

python – SQL查询输出到.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

我错过了什么?

解决方法:

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')

希望这可以帮助!

标签:export-to-csv,python,csv,api
来源: https://codeday.me/bug/20191001/1840143.html