PyMySQL,MySQL,Python:字符串格式

时间:2018-02-13 12:22:47

标签: python mysql pymysql

我无法在SO上找到解决方案,所以我最后的选择就是问这个问题。我在MySQL上运行代码,一切似乎都很好,但是当我在Python中运行代码时,我收到一个错误:%d format: a number is required, not str,这是PyMySQL的故障吗?这两个%s应该是apple的占位符,而%d%b%y应仅在SQL命令中使用,并且不会充当命令外的占位符。

db.query("""SELECT *, DATE_FORMAT(DATE_ADD
            ('1970-01-01 00:00:00',INTERVAL pubtime SECOND),
            '%d %b %Y') AS pubdate FROM media
            WHERE MATCH (description) AGAINST (%s
            IN BOOLEAN MODE) OR MATCH (headline) AGAINST (%s
            IN BOOLEAN MODE) ORDER BY pubtime DESC LIMIT 5""",
            ('apple', 'apple'))

1 个答案:

答案 0 :(得分:0)

你可以逃脱'%'通过添加另一个'%'在它之前。

db.query("""SELECT *, DATE_FORMAT(DATE_ADD
        ('1970-01-01 00:00:00',INTERVAL pubtime SECOND),
        '%%d %%b %%Y') AS pubdate FROM media
        WHERE MATCH (description) AGAINST (%s
        IN BOOLEAN MODE) OR MATCH (headline) AGAINST (%s
        IN BOOLEAN MODE) ORDER BY pubtime DESC LIMIT 5""",
        ('apple', 'apple'))