0

I am looking at some older Python scripts that I am modernising and within query strings they used this format:

query = " SELECT DISTINCT account from customers..accounts WHERE date = '" + date + "'"
cursor.execute(query)

I would have thought this should be performed this by using the following format:

query = " SELECT DISTINCT account from customers..accounts WHERE date = {}".format(date)
cursor.execute(query)

When would you use the original format? Is there a reason to use it? Does it concatenate? Why would you concat within a SQL query?

Personally I have always run my sybase queries using the module:

cursor.execute("SELECT DISTINCT account from customers..accounts WHERE date = @date", {"@date": date})
tripleee
  • 175,061
  • 34
  • 275
  • 318
SimonT
  • 974
  • 1
  • 5
  • 9
  • 2
    When the thing you're formatting is SQL queries, you should never use either - let the DB driver interpolate the values. But yes, `+` on strings is concatenation. – jonrsharpe Apr 07 '21 at 08:23
  • What is your SQL database? – Tim Biegeleisen Apr 07 '21 at 08:25
  • This project uses Sybase – SimonT Apr 07 '21 at 08:25
  • @jonrsharpe I forgot to add the method I actually use which is using the module / driver. I just wasn't sure why anyone would use the method of + var + within a query... doesn't make sense why would you concat within a query – SimonT Apr 07 '21 at 08:38
  • 1
    Why aren't you migrating everything to that (correct) approach? If you want to know more about the trade-offs of the different string formatting options (_all_ wrong in this case) see e.g. https://stackoverflow.com/q/38722105/3001761, https://stackoverflow.com/q/34619384/3001761, https://stackoverflow.com/q/41481263/3001761, https://stackoverflow.com/q/10043636/3001761, ... – jonrsharpe Apr 07 '21 at 08:47
  • I will be migrating to it. My question was asking WHY would it have been done this way? Is there a reason behind why it would have been done this way? I was just trying to understand why. – SimonT Apr 07 '21 at 08:50

1 Answers1

2

Simply change it to the driver method you detailed at the bottom.

I can't answer why it was done that way as it does not make any sense to do it with concatenated strings.

E_net4
  • 27,810
  • 13
  • 101
  • 139
riker87
  • 36
  • 2
  • Yea that's what I'm going to do. I guess no one knows why the previous coder did it this way. – SimonT Apr 07 '21 at 09:00