【问题标题】:Sqlite "OperationalError: near "05": syntax error"Sqlite“OperationalError:靠近“05”:语法错误”
【发布时间】:2021-04-22 10:26:51
【问题描述】:

我正在使用 sqlite,并且在处理日期和时间方面有些困难。我创建了一个表,其字段为Date,类型为text

我需要将该字段设置为自定义时间,f。例如:'2021-01-18 05:07:37' 我使用这段代码得到的(我现在使用 datetime 作为示例)

date = datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S')
print(date)
# 2021-01-18 05:07:37

然后我用这个日期创建一条记录:

command = f'''INSERT INTO Twitter (Date, Content)
                VALUES(datetime({date}), "Some cool content")'''
print(command)
# INSERT INTO Twitter (Date, Content)
            VALUES(datetime(2021-01-18 05:13:54), "Some cool content")
conn.execute(command)
conn.commit()

此代码引发错误:

操作错误
Traceback(最近一次通话最后一次)


2 VALUES(datetime({date}), "一些很酷的内容")'''
3 打印(命令)
----> 4 conn.execute(命令)
5 conn.commit()

OperationalError:接近“05”:语法错误

我不确定出了什么问题,我认为我正确使用了 sqlite 日期时间格式,但该错误似乎与格式有关,有什么建议可以解决这个问题吗?

编辑

我注意到,如果我手动将日期添加到 sqlite 命令,效果很好,就像这样做:

command = f'''INSERT INTO Twitter (Date, Content)
                VALUES(datetime('2021-01-18 05:07:37'), "Some cool content")'''

当我将日期时间动态添加为变量时出现此问题,我不确定是否遗漏任何内容。

【问题讨论】:

  • 永远不要使用其他字符串格式的f-strings来构造SQL。这不安全,会导致像你这样的错误。查看数据库适配器的文档,了解如何为 execute() 提供参数。
  • @KlausD。这似乎是问题所在,如果我手动添加值没有错误
  • 这不是问题。在第一个示例中,您缺少日期/时间周围的单引号 (')。

标签: python python-3.x sqlite


【解决方案1】:

问题是 sqlite 不熟悉 python 的 datetime 类型,因此通过尝试将 datetime(2021-01-18 05:13:54) 插入到 Date 字段中,您将收到 OperationalError: near "05": syntax error 并且当您添加单引号时 '2021-01-18 05:07:37' 日期转换为字符串,可以插入到表格中。
你可以尝试做

command = f'''INSERT INTO Twitter (Date, Content)
                VALUES(datetime('{date}'), "Some cool content")'''

command = f'''INSERT INTO Twitter (Date, Content)
                VALUES(datetime("{date}"), "Some cool content")'''

注意:sqlite datetime 函数需要一个字符串,如此处所述 https://sqlite.org/lang_datefunc.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-11
    • 2019-02-07
    • 2020-02-06
    • 2019-01-12
    • 2014-05-17
    • 2021-10-19
    • 2018-07-27
    • 1970-01-01
    相关资源
    最近更新 更多