0

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

+-------------+---------------------+------+-----+---------+-------+
4

2 に答える 2

4

文字列の書式設定や手動の引用の代わりに、パラメーター化された SQL を使用します。

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

これはより簡単で、 SQL インジェクションの防止に役立ちます。

于 2013-05-21T20:30:59.173 に答える
-1

次のように、テーブル名の後にスペースを挿入し、テキストを "" の中に入れてみてください。

cursor.execute('INSERT INTO tweets (created_at) VALUES ("{created_at}")'.format(created_at=t)) 
于 2013-05-21T20:30:40.087 に答える