0

I want to add quotes i.e. '' around my input_date in the following sql query.

sql = "select num_store, sum(gross_sales) as gross_sales from dtm.sales where day = " + input_date + " and num_store = '" + store + "' GROUP BY num_store"

The dates I am querying on are of type ANSIDATE. I want to add the '' around the input date as cleanly as possible so that it would still detect the fields.

The query that I am running directly on the vectorwise database using SQuirrel SQL CLient to verify is like so:

SELECT num_store, sum(gross_sales) as gross_sales FROM dtm.sales WHERE day = '2019-06-21' AND num_store = 69 GROUP BY num_store
2
  • What version of SQL are you using? Commented Jul 23, 2019 at 9:19
  • The version I am using is sqlite3 Commented Jul 23, 2019 at 9:23

3 Answers 3

2

You should be using a prepared statement:

import sqlite3

# obtain connection and cursor
sql = """select num_store, sum(gross_sales) as gross_sales
         from dtm.sales 
         where day = ? and num_store = ?
         group by num_store"""
params = (input_date, store,)
c.execute(sql, params)
# c.fetchall()

Using a prepared statement frees you from worrying about how to escape the literal values in your query.

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

1 Comment

Thanks ! But I need the sql request to stay the same for the sake of the whole project and the behavior of the django-rest-framework api I am developing
1
query = """ select num_store, sum(gross_sales) as gross_sales from 
 dtm.sales where day = {input_date} and num_store = {input_store} GROUP BY 
 num_store """

dict = new Dict()
dict['input_date'] = datetime.strptime(value, '%Y-%m-%d ')
dict['input_store'] = value
query.format(**dict)

8 Comments

It didn't work ! How to apply what you suggested to the first query which is inside Python not the second one that is being used to test directly against the database ?
what import to use for dict ?
@S.Jackson You dont need to import dictionary it is in standard lib
I used it and I get this error AttributeError: 'str' object has no attribute 'strftime'
My date is only YYYY-MM-DD
|
1

If I've understood your problem, you'll need to convert this 'ANSIDATE' in a string. Your ANSIDATE follows this pattern '%Y-%m-%d' (yyyy-mm-dd) and you could do:

sql = "select num_store, sum(gross_sales) as gross_sales from dtm.sales where day = " + input_date.strftime('%Y-%m-%d') + ...

2 Comments

from where do you get .strftime ?? is there an import i should make ?
import datetime

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.