从Django调用MySQL中的DATE_FORMAT()失败 [英] Calling DATE_FORMAT() in MySQL from Django fails
问题描述
我可以运行SET
语句来分配变量,并使用事务"在mySQL会话中对其进行维护,但是当我包含函数DATE_FORMAT
时,如下所示:
I can run SET
statements to assign variables and use "transaction" to maintain it in the mySQL session, but when I include the function DATE_FORMAT
like this:
cursor.execute("SET @dowToday:=CAST( DATE_FORMAT( NOW(), '%w' ) AS UNSIGNED);")
Django抱怨
execute行151的/usr/lib/pymodules/python2.6/MySQLdb/cursors.py中的格式字符串参数不足,
not enough arguments for format string in /usr/lib/pymodules/python2.6/MySQLdb/cursors.py in execute, line 151
删除CAST或使用引号或将其转义都无济于事.
It doesn't help to remove the CAST or to play with or escape the quotes.
有想法吗?
推荐答案
我完全错过了上一个答案中的要点.这是Django游标.不是标准Python".
I totally missed the point in my previous answer. This is a Django cursor. Not a "standard Python" one.
根据文档:
https://docs.djangoproject.com/en/dev/topics /db/sql/
请注意,如果您要在查询中包含文字百分号, 如果要传递参数,则必须将它们加倍:
Note that if you want to include literal percent signs in the query, you have to double them in the case you are passing parameters:
cursor.execute("SELECT foo FROM bar WHERE baz = '30%%' and id = %s", [self.id])
我认为,如果这不起作用,您可能会退回到一些简单而又愚蠢的把戏:
I assume if this does not work, your could fallback to some simple-and-stupid trick:
cursor.execute("SET @dowToday:=CAST( DATE_FORMAT( NOW(), '%sw' ) AS UNSIGNED);", ['%'])
%s
将替换为作为参数传递的%
...
The %s
will be replaced by the %
passed as an argument...
这篇关于从Django调用MySQL中的DATE_FORMAT()失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!