如何在 Python 中将日期传递给 MySQLdb?

How do I pass a date to MySQLdb in Python?

我正在尝试做一个相当简单的 SELECT,将日期作为变量。但我总是收到数据类型错误:

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)

抛出异常:

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'`

我的数据库有数据:

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

有什么想法吗?谢谢

看起来是一个简单的错字。 Python 字符串格式化表达式应该像 '%s'%variable 而不是 ('%s') % variable

具体来说,使用

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

或考虑使用带有 ? 占位符的推荐语法(参见 https://docs.python.org/2/library/sqlite3.html#sqlite3.Cursor.execute):

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

你的查询行基本上是:

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

它将% 运算符应用于cur.execute('QUERY') return 值,它是整数。因此你收到 TypeError - long % datetime is not defined for long type,你实际上想做 string % something 操作。

要执行字符串格式化,您必须将 % 运算符移动到 cur.execute 参数 - 将其命名为 cur.execute('QUERY' % today).