1

Hello i am trying to load a huge query (5000+ lines) from a text file and execute the whole query at the once using the code below. How can i load my query from a txt file and execute it using python pandas

i opened up my text file using the code below

query1 = open("Script.txt","r")

and tried executing the script with the code below.

df_ora1 = pd.read_sql(query1, con=connection1)

I am getting the following error

DatabaseError: Execution failed on sql '<_io.TextIOWrapper expecting string or bytes object

my text file has """ start query

end query """

2
  • Use query1 = open("Script.txt","r").read() Commented Jul 30, 2020 at 14:49
  • Always store sql queries in .sql files Commented Jul 30, 2020 at 14:50

1 Answer 1

3
  1. for standalone - I create sql, then write it to a file
  2. your solution - read sql from file. Pass it to read_sql() along with connection
temptable = "tempx"
sql = f"""select Year, count(*) as c 
                        from {temptable} 
                        where Month=1 
                        and Sharpe between 1 and 2 
                        and stock like '%%2%%'
                        group by Year"""
with open("script.sql","w") as f: f.write(sql)
# read sql script from file.  pass it to pandas with connection
with open("script.sql") as f: sql = f.read()
engine = sqlalchemy.create_engine('mysql+pymysql://sniffer:[email protected]/sniffer')
conn = engine.connect()
print(pd.read_sql(sql, conn).to_string(index=False))

output

 Year    c
 2018  930
 2019  932
 2020  958
Sign up to request clarification or add additional context in comments.

Comments

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.