-1

The SQL query is stored in a notepad file. Need to run this using Python scripts

cursor = connection.cursor()
with open('C:\Python_Script_Test\SQL_Query.txt','r') as inserts:
   query = inserts.read()
cursor.execute(query)

Expected is that the query should execute.

Actual getting below error:

with open('C:\Python_Script_Test\SQL_Query.txt','r') as inserts: " syntax error: (unicode error) 'unicodeescape' codec cant decode bytes in position 2-3: truncated \UXXXXXXXX escape

error is pointing at the comma inserted in the above line just before mode. tried replacing single quotes with double but no luck also, my query is multi line.

Please help

Neha M
  • 1
  • 2
  • Does this answers your question ? https://stackoverflow.com/questions/2953834/how-should-i-write-a-windows-path-in-a-python-string-literal – Kostas Nitaf May 08 '23 at 11:53
  • You have backslashes in your path, not sure that this is your problem, but try to use either a raw string literal `r"C:\Python_Script_Test\......"` or escaping the backslash like `"C:\\Python_Script_Test\\......"` – Talon May 08 '23 at 11:54
  • You answer has not enough information. What encoding the file has? – Sergey Zaykov May 08 '23 at 12:06
  • escaping the backlash is the correct way.....was able to resolve then. Thanks – Neha M May 08 '23 at 13:32

2 Answers2

-1

As you have a utf8 encoding you need to tell it to the app

cursor = connection.cursor()
with open('C:\\Python_Script_Test\\SQL_Query.txt','r', encoding="utf-8") as inserts:
   query = inserts.read()
cursor.execute(query)

of course there could be other UTf encioding envolved

nbk
  • 45,398
  • 8
  • 30
  • 47
  • This is working. adding the encoding parameter is solving the issue very nicely. Many Thanks !! – Neha M May 08 '23 at 13:31
-1
cursor = connection.cursor()
with open('C:\\Python_Script_Test\\SQL_Query.txt','r', encoding="utf-8") as inserts:
   query = inserts.read()
cursor.execute(query)

this is solving the issue. Addition of encoding parameter and escaping the backslash "\" resolved this issue.

Thanks for the help !!

Jose Manuel de Frutos
  • 1,040
  • 1
  • 7
  • 19
Neha M
  • 1
  • 2