【问题标题】:Insert datetime.datetime object in MySQL在 MySQL 中插入 datetime.datetime 对象
【发布时间】:2013-05-21 20:18:19
【问题描述】:

我正在尝试将我的 datettime 对象插入 MySQL

>>> t
datetime.datetime(2013, 5, 21, 19, 33, 36, tzinfo=tzutc())
>>> cursor.execute('INSERT INTO tweets(created_at) VALUES ({created_at})'.format(created_at=t))

我得到的错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py", line 174, in execute
    self.errorhandler(self, exc, value)
  File "/usr/lib/python2.7/dist-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler
    raise errorclass, errorvalue
_mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '19:33:36+00:00)' at line 1")
>>> 

MySQL:

mysql> DESCRIBE mytable;
+-------------+---------------------+------+-----+---------+-------+
| Field       | Type                | Null | Key | Default | Extra |
+-------------+---------------------+------+-----+---------+-------+

| created_at  | datetime            | YES  |     | NULL    |       |

+-------------+---------------------+------+-----+---------+-------+

【问题讨论】:

  • 尝试:>>> cursor.execute('INSERT INTO tweets (created_at) VALUES ("{created_at}")'.format(created_at=t)) 注意空格和“
  • 我对数据库一无所知,但您使用的字符串格式将在您的日期时间对象上隐式调用str 并使用该字符串替换{created_at}。从错误来看,该字符串似乎是导致 mysql 阻塞的原因。
  • 你说的太对了! @Gustavo Vargas,谢谢它的工作原理
  • 不错!好吧,我把它作为答案,如果你同意我会很高兴!

标签: python mysql sql mysql-python


【解决方案1】:

使用参数化 sql 代替字符串格式化和手动引用:

cursor.execute('INSERT INTO tweets(created_at) VALUES (%s)', [t])

这更容易,并且有助于防止sql injection

【讨论】:

    【解决方案2】:

    尝试在你的表名后插入一个空格并将你的文本放在“”中,如下所示:

    cursor.execute('INSERT INTO tweets (created_at) VALUES ("{created_at}")'.format(created_at=t)) 
    

    【讨论】:

    • 应避免使用format 字符串方法。变量不会被转义,您将遇到 SQL 注入问题。有关该问题,请参阅Django's docs
    • 我同意你的观点,但在他的情况下,这个变量仅来自内部代码。这也需要注射吗?我不是在讽刺,我真的是在问你,我不是一个净化编码方面的知识。
    • 最好始终保持标准化,并且每次都以正确的方式做事。它将避免混淆,以及在不考虑可能引入问题的情况下使用或复制代码的可能性。
    猜你喜欢
    • 2010-11-11
    • 2019-03-17
    • 1970-01-01
    • 1970-01-01
    • 2012-05-18
    • 2020-09-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多