Skip to content Skip to sidebar Skip to footer

Read External Sql File Into Pandas Dataframe

This is a simple question that I haven't been able to find an answer to. I have a .SQL file with two commands. I'd like to have Pandas pull the result of those commands into a Data

Solution 1:

I have a solution that might work for you. It should give you a nice little pandas.DataFrame.

First, you have to read the query inside the sql file. Then just use the pd.read_sql_query() instead of pd.read_sql()

I am sure you know it, but here is the doc for the function: http://pandas.pydata.org/pandas-docs/version/0.20/generated/pandas.read_sql_query.html#pandas.read_sql_query

# Read the sql file
query = open('filename.sql', 'r')

# connection == the connection to your database, in your case prob_db
DF = pd.read_sql_query(query.read(),connection)
query.close() 

I can assure you that it is working with T-SQL, but I never used it with MySQL.

Solution 2:

This is a MWE of how it worked for me:

query = open('./query_file.sql', 'r') 

db_config = {
            'server': server address,
            'port': port,
            'user': user,
            'password': password,
            'database': db name
        }

    try:
        sql_conn = pymssql.connect(**db_config)
        logging.info('SQL connection is opened')       
        avise_me_df = pd.read_sql(query.read(),sql_conn)
        logging.info('pandas df recorded')
    except OperationalError as e:
        connected = False

        logging.error('Error reading data from SQL table')
    else:
        connected = Truefinally:
        if connected:
            sql_conn.close()
            logging.info('SQL connection is closed')

I hope this might help.

Post a Comment for "Read External Sql File Into Pandas Dataframe"