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})
6
  • 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. Commented Apr 7, 2021 at 8:23
  • What is your SQL database? Commented Apr 7, 2021 at 8:25
  • This project uses Sybase Commented Apr 7, 2021 at 8: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 Commented Apr 7, 2021 at 8: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. stackoverflow.com/q/38722105/3001761, stackoverflow.com/q/34619384/3001761, stackoverflow.com/q/41481263/3001761, stackoverflow.com/q/10043636/3001761, ... Commented Apr 7, 2021 at 8:47

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Yea that's what I'm going to do. I guess no one knows why the previous coder did it this way.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.