wsteven
wsteven

Reputation: 67

How do I pass a date to MySQLdb in Python?

I'm trying to do a rather simple SELECT with a date as a variable. But I always end up receiving a datatype error :

today = datetime.datetime.date(datetime.datetime.now())
cur.execute('select nom from agenda,taverniers where agenda.id_t = taverniers.id_t and agenda.thedate = "%s"') %(today)

It throws an exception:

moncal.py:61: Warning: Incorrect date value: '%s' for column 'thedate' at row 1
cur.execute('select nom from agenda,taverniers where agenda.id_t = taverniers.id_t and agenda.thedate = "%s"') %(today)
(...)
TypeError: unsupported operand type(s) for %: 'long' and 'datetime.date'`

My database has data:

mysql> select * from agenda
    -> ;
+------+------+------------+
| id_t | id_c | thedate    |
+------+------+------------+
|    3 |    5 | 2015-12-12 |
|    1 |    6 | 2015-12-24 |
+------+------+------------+

Any idea? Thanks.

Upvotes: 0

Views: 1719

Answers (2)

Łukasz Rogalski
Łukasz Rogalski

Reputation: 23233

Your line with query is basically:

cur.execute('QUERY') % (today)

It applies % operator to cur.execute('QUERY') return value, which is integer. Therefore you receive TypeError - long % datetime is not defined for long type, and you actually want to do string % something operation.

To perform string formatting you'll have to move % operator to cur.execute argument - call it like cur.execute('QUERY' % today).

Upvotes: 1

LiMar
LiMar

Reputation: 2972

Looks to be a simple typo. Python expression for string formatting should be like '%s'%variable rather then ('%s') % variable

Specifically, use

cur.execute('select nom from agenda,taverniers where agenda.id_t = taverniers.id_t and agenda.thedate = "%s"' % today)

Or consider using recommended syntax (see https://docs.python.org/2/library/sqlite3.html#sqlite3.Cursor.execute) with ? placeholders:

cur.execute('select nom from agenda,taverniers where agenda.id_t = taverniers.id_t and agenda.thedate = "?"',(today,))

Upvotes: 1

Related Questions