0

I have a problem using backslashes with ' in a query launched in python. This is the query:

c.execute("SELECT Num FROM Table WHERE cie = 'TAB_' AND tablecode = 'IDL\DOC\'TAB_'\'{G}'\'FV'\'          ' ' ".format(G=date.today().year))

the problem is that even if I do something like this :

c.execute("SELECT Num FROM Table WHERE cie = 'TAB_' AND tablecode = 'IDL\\DOC\\'TAB_'\\'{G}'\\'FV'\\'          ' ' ".format(G=date.today().year))

it gives me the same error:

pyodbc.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Incorrect syntax near 'TAB_'. (102) (SQLExecDirectW)")

My field in sql contains values like this : VALUE1\VALUE2'VALUE3'\' ' So I have to use backslashes How can I do it?

IT-SRL
  • 37
  • 7
  • Can you post some sample data so that someone can replicate the SQL query? There is an issue with your apostrophes in the tablecode section. – JonTout Jun 23 '22 at 09:40
  • You have unescaped single quotes in your literal. – Thom A Jun 23 '22 at 09:41
  • **Parameterize your query**, this fixes your problem and also deals with your injection vulnerability. If you *really* cannot parameterize then escape the quote by doubling it – Charlieface Jun 23 '22 at 09:57
  • [Why should you use parameters](https://stackoverflow.com/questions/7505808/why-do-we-always-prefer-using-parameters-in-sql-statements) – HoneyBadger Jun 23 '22 at 09:57
  • I parameterized my query but it still doesn't work @Charlieface – IT-SRL Jun 23 '22 at 12:40
  • So your code is now `c.execute("SELECT Num FROM Table WHERE cie = 'TAB_' AND tablecode = ?", ( "IDL\DOC\'TAB_'\'{G}'\'FV'\' ".format(date.today().year), ))` right? – Charlieface Jun 23 '22 at 12:46
  • Yes and it doesn't work, it only works writing it in this way : c.execute("SELECT Num FROM table WHERE cie = 'TAB_' AND tablecode = 'IDL\DOC\\''TAB_''\\''{G}''\\''FV''\\'' '' ' ".format(G=date.today().year)).fetchone()[0] @Charlieface – IT-SRL Jun 23 '22 at 13:00
  • You are going to have to show the exact code you have currently, that should work. What error are you getting? – Charlieface Jun 23 '22 at 13:04
  • TypeError: 'NoneType' object is not subscriptable, so basically there's no result with that condition, meaning that it's written wrongly – IT-SRL Jun 23 '22 at 13:06

0 Answers0