【问题标题】:inserting datetime into database将日期时间插入数据库
【发布时间】:2019-10-06 04:37:17
【问题描述】:

谁能解释如何使用 python 将日期时间插入 SQLite 数据库? 哪个数据类型应该是日期时间,我尝试了很多不同的方法

我的疑惑是基于cs50中的问题集7,我们使用flask作为web框架

history 是数据库的名称 transaction 是字段名称

db.execute("INSERT INTO history (transaction) VALUES(:d)",
             d=datetime.datetime.today())

错误消息,我在运行应用程序时收到此消息

builtins.RuntimeError
RuntimeError: near "transaction": syntax error [SQL: "INSERT INTO history (transaction) VALUES('2019-05-19 17:14:25')"] (Background on this error at: http://sqlalche.me/e/e3q8)

【问题讨论】:

    标签: python-3.x sqlite datetime sql-insert


    【解决方案1】:

    transaction 是 SQLite 中的 reserved word

    sqlite> INSERT INTO history (transaction) VALUES('2019-05-19 17:14:25');
    Error: near "transaction": syntax error
    

    为了消除保留字的歧义,必须特别引用它们。在这种情况下,作为带双引号的标识符。

    sqlite> INSERT INTO history ("transaction") VALUES('2019-05-19 17:14:25');
    

    与其不断记住引用transaction,我建议重命名该列; created_at 对于行时间戳非常常见。我也推荐using an ORM rather than writing SQL by hand;它将为您处理所有报价,并具有许多其他好处。

    【讨论】:

    • 我试过你说的没有错误,但是当我看到数据库时 created_at 的值为'NULL',你能告诉它为什么会发生
    猜你喜欢
    • 2012-05-01
    • 2013-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-20
    相关资源
    最近更新 更多