Create a String with Quotes

Viewed 379

I have a code like -

from datetime import date
today = date.today()
sql_command = "select * from [dbo].[DB_Name] where DT like " + str(today) + '%'

But I want my string to look like this -

select * from [dbo].[DB_Name] where DT like 'today%'

I am strugling to put quotes on the date - it should be '2021-01-11%'. How can I do it? I have tried to format the today first but i am unable to do it.

3 Answers

NEVER USE STRING INTERPOLATION FOR A SQL-QUERY!

All SQL languages has a way to pass in parameterized queries, i.e. queries along with parameters. This will pre-compile the statement before adding the arguments, making it impossible to do a SQL-injection, the biggest security issue on the web to date.

If you're using psycopg2, you can create your query as a parameterized query by something like this:

sql_query = "select * from [dbo].[DB_Name] where DT like '%s%%'"
cursor.execute(sql_query , [today.strftime("%Y-%m-%d")])

Here, sql_query will contain select * from [dbo].[DB_Name] where DT like '%s%%'.

The %s is where to put in the argument, and the %% is to put in a single percentage sign (must use two so the percentage sign isn't confused for the start of a parameter). And also, in Python you can have either ' or " in your string if you just make sure to start with the other of them.

As pointed out by Ted in the comments, interpolation of commands can cause major security issues such as SQL injections.

Coming over to your query, you can do it by using single-quotes inside double-quotes.

print("'hello'")

will print

'hello'

I don't know anything about SQL commands by interpretation, and from what I am told DON'T DO THIS, but here is how to do what you're asking:

"select * from [dbo].[DB_Name] where DT like '" + str(today) + "%'"

If you use double quotes for your string definition, you can easily use single quotes for single quotes (the opposite is true too)

Related