如何使用pandas pd.read_sql导出到csv?

时间:2019-04-17 17:39:21

标签: python-3.x

我有一个查询数据库的python函数,当我不转换为数据帧时,如何将其写入csv?还是必须导入数据框并使用该功能?

返回可以很好地在我的控制台上查看结果,但是现在我想导出为csv。

任何帮助将不胜感激。

代码:

import pandas as pd
import pyodbc, os 
import datetime
from datetime import datetime
from pandas import ExcelWriter
import numpy as np


    def date(businessDate):
        con = pyodbc.connect(r'DSN='+'Stack',autocommit=True)  
        print('working')


        sql = f"""
        SELECT * FROM date 
        where businessDate = {businessDate}

        """

        df_date = pd.read_sql(sql,con)

        con.close()

        return(df_date)

1 个答案:

答案 0 :(得分:1)

似乎df_date = pd.read_sql(sql,con)产生一个数据帧。您可以通过运行type(df_date)进行测试。

请参见write_to_csv()下的函数,该函数与具有date()功能的df_date.to_csv()基本上相同。在运行write_to_csv()之前,请确保csv文件已经存在,因为此函数只会写入该文件,而不创建它。

import pandas as pd
import pyodbc, os 
import datetime
from datetime import datetime
from pandas import ExcelWriter
import numpy as np


def date(businessDate):
    con = pyodbc.connect(r'DSN='+'Stack',autocommit=True)  
    print('working')
    sql = f""" 
    SELECT * FROM date 
    where businessDate = {businessDate}
    """
    df_date = pd.read_sql(sql,con)
    con.close()
    return(df_date)

path = "C:\\Users\\path\\to\\your\\folder\\file.csv"

def write_to_csv(businessDate):
    con = pyodbc.connect(r'DSN='+'Stack',autocommit=True)  
    print('working')
    sql = f""" 
    SELECT * FROM date 
    where businessDate = {businessDate}
    """
    df_date = pd.read_sql(sql,con)
    con.close()
    df_date.to_csv(path)
    return('Successfully wrote to csv')