2

I am trying to return a date selected from date picker in to my sql query in my python code. I also tried using encode(utf-8) to remove the unicode string but still, I am getting the error.

I am new to python. Can anyone please help me figure out how to solve this problem? I am using python flask to create the webpage

if request.method=='POST':
        dateval2 = request.form['datepick']
        dateval = dateval2.encode('utf-8')
    result = ("SELECT * FROM OE_TAT where convert(date,Time_IST)='?'",dateval
    df = pd.read_sql_query(result,connection)`

Error:

pandas.io.sql.DatabaseError
DatabaseError: Execution failed on sql '("SELECT * FROM OE_TAT where convert(date,Time_IST)='?'", '2015-06-01')': The first argument to execute must be a string or unicode query.
doru
  • 9,022
  • 2
  • 33
  • 43
keerthi kumar
  • 105
  • 1
  • 2
  • 6
  • In which format comes the date from the date picker? – doru Jun 24 '15 at 07:30
  • Format : "yy-mm-dd" same as my sql server database format – keerthi kumar Jun 24 '15 at 07:41
  • This is the exact error i am getting : pandas.io.sql.DatabaseError DatabaseError: Execution failed on sql '("SELECT * FROM OE_TAT where convert(date,Time_IST)='?'", '2015-06-02')': The first argument to execute must be a string or unicode query. – keerthi kumar Jun 24 '15 at 07:43
  • You are providing a tuple to [`read_sql_query`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_sql_query.html), while the first argument (the query) has to be a string – joris Jun 24 '15 at 12:42

1 Answers1

6

You are providing a tuple to read_sql_query, while the first argument (the query) has to be a string. That's why it gives the error "The first argument to execute must be a string or unicode query".

You can pass the parameter like this:

result = "SELECT * FROM OE_TAT where convert(date,Time_IST)=?"
df = pd.read_sql_query(result, connection, params=(dateval,))

Note that the use of ? depends on the driver you are using (there are different ways to specify parameters, see https://www.python.org/dev/peps/pep-0249/#paramstyle). It is possible you will have to use %s instead of ?.

You could also format the string in beforehand, like result = "SELECT * FROM OE_TAT where convert(date,Time_IST)={0}".format(dateval), however, this is not recommended, see eg here

Community
  • 1
  • 1
joris
  • 133,120
  • 36
  • 247
  • 202