1

I have query in .txt file and i am trying to run that query using python. it is working fine if my query written in single line. but my query had multiple lines in text file. it is giving syntax error as it is reading only first line.

i have tried below code

cursor = cnxn.cursor()
with open('C:\Python_Script_Test\INSERTS.txt','r') as inserts:
    for statement in inserts:
        cursor.execute(statement)

i have big query with multiple lines in it. can you please suggest the best code to read all the lines to run query.

1
  • Did you try this solution ? It might help you. Commented Apr 23, 2019 at 13:01

2 Answers 2

2

Try using .read()

Ex:

cursor = cnxn.cursor()
with open('C:\Python_Script_Test\INSERTS.txt','r') as inserts:
    query = inserts.read()
cursor.execute(query)
Sign up to request clarification or add additional context in comments.

Comments

0

.read() works for single line query. For multiline query Python creates list of lines. You can collate lines together using .append(), but you will need to add CRLF markers at the end of each line that are readable by SQL server ...

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.