0

I have a python function that queries a database, how can I write this to csv when I do not convert to dataframe? Or must I import dataframe and use that function?

Return works fine to see results in my consol, but now I would like to export as csv.

any help would be appreciated.

code:

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 Answer 1

1

It appears df_date = pd.read_sql(sql,con) produces a dataframe. You can test this by running type(df_date).

See function below write_to_csv() which is essentially the same function as date() with df_date.to_csv() function. Ensure the csv file already exists before running write_to_csv() since this function will only write to it and not create it.

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')
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks Angel. Can you explain to me how and where in the code it become a dataframe? Also why is path in the first function?
df_date = pd.read_sql(sql,con) should produce a dataframe. You can test this by running type(df_date) and it should return pandas.core.frame.DataFrame. Path will direct where the csv file is located and allows the function df_date.to_csv() to write to it.
thanks, could the path been stored in the write_to_csv function?
Yes you can store it in the to_csv function. df_date.to_csv(C:\\path\\to\\file.csv)
so much import for a simple task. why oh why python

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.