【问题标题】:Python SQLite3 InsertPython SQLite3 插入
【发布时间】:2016-07-08 17:13:07
【问题描述】:

我在插入值时遇到错误。我的数据库有 3 列。此处初始化一个自增整数:

connection.execute("CREATE TABLE IF NOT EXISTS {tn} ({nf1} {ft1} PRIMARY KEY AUTOINCREMENT)"\
    .format(tn = tableName, nf1 = "IDPK", ft1 = "INTEGER"))

和两个这样初始化的文本字段:

connection.execute("ALTER TABLE {tn} ADD COLUMN '{cn}' {ct}".format(tn = tableName, cn = "foo", ct = "TEXT"))
connection.execute("ALTER TABLE {tn} ADD COLUMN '{cn}' {ct}".format(tn = tableName, cn = "bar", ct = "TEXT"))

执行在这里:

connection.execute("INSERT INTO {tn} VALUES (NULL, {col1}, {col2})".format(tn = tableName, col1 = text1, col2 = text2))

而抛出的错误是:

sqlite3.OperationalError: no such column: "obfuscatedTextStringInText1"

我不明白为什么它认为列名在 text1 中。我将一个值插入到我认为使用这种语法的第 1 列和第 2 列中,作为使用 NULL 关键字的自动增量函数。

【问题讨论】:

  • 我认为在sqlite3中null的默认值是""。尝试只为 col1 和 col2 列添加值。

标签: python sqlite


【解决方案1】:

不要使用字符串格式在查询中插入变量。这很危险(你很容易受到SQL injection attacks 的攻击)和错误提示(正如你已经看到的那样)。

相反,参数化您的查询:

connection.execute("""
    INSERT INTO 
        {tn} 
    VALUES 
        (NULL, :col1, :col2)""".format(tn=tableName), 
    {"col1": text1, "col2": text2})

请注意,我们 cannot parameterize table or column names - 确保您验证并正确转义 tableName,或信任您的来源。

【讨论】:

    【解决方案2】:

    {col1}{col2} 周围应该有引号,因为它们是作为文本值插入的。例如,它目前正在被评估为:

    "INSERT INTO table_name VALUES (NULL, my text 1, my text 2)"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-21
      • 2014-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-11
      • 2019-01-30
      • 1970-01-01
      相关资源
      最近更新 更多