【问题标题】:psycopg error, column does not existpsycopg 错误,列不存在
【发布时间】:2017-01-05 00:09:16
【问题描述】:

我不断收到这个

错误:psycopg2.ProgrammingError:列“someentry”不存在。

someentry 不是列时,错误表明列someentry 不存在,它只是一个要输入到数据库中的值。

这是给出错误的代码:

cur.execute('INSERT INTO {0!s} (ip_id, item) VALUES ({1!s}{2!s})'.format('mytable',1,'someentry'))

这是我创建表格的方式:

tablename = 'mytable'
command = """
          CREATE TABLE IF NOT EXISTS {} (
                ip_id SERIAL PRIMARY KEY,
                item VARCHAR(255) NOT NULL
          )
          """.format(tablename)

cur.execute(command)

【问题讨论】:

    标签: postgresql python-3.x psycopg2


    【解决方案1】:

    您必须在查询中使用单引号。

    我收到了同样类型的错误

    cur.execute('insert into my_table(id, name, horse_type, horse_code, horse_name) values(default, %s, 3, %s, "Mary Wonder")', [e[0], e[1]])
    

    它产生了

    Traceback (most recent call last):
    File "process_horse.py", line 11, in <module>
    [e[0], e[1]])
    psycopg2.ProgrammingError: column "Mary Wonder" does not exist
    LINE 2: ', "Mary Wonder")
           ^
    

    显然它是数据,而不是列名,就像您说的那样。
    当我将其更改为

    cur.execute("insert into my_table(id, name, horse_type, horse_code, horse_name) values(default, %s, 3, %s, 'Mary Wonder')",[e[0], e[1]])
    

    它没有错误。

    【讨论】:

      【解决方案2】:

      导致这个错误的问题是因为你忘记在{1!s}{2!s}之间添加一个逗号,而且你也没有转义字符串'someentry'所以postgres认为它是一个列名标识符。

      解决方案是修复语法错误和转义值。以下是正确的做法:

      cur.execute(
          'INSERT INTO mytable (ip_id, item) VALUES (%s, %s)',
          (1, 'someentry')
      )
      

      如果表名也是变量,既然表名是标识符就需要use extension AsIs

      from psycopg2.extensions import AsIs
      
      cur.execute(
          'INSERT INTO %s (ip_id, item) VALUES (%s, %s)',
          (AsIs('mytable'), 1, 'someentry')
      )
      

      【讨论】:

      • 菲利普,谢谢。有效。但是你能解释一下“转义字符串”是什么意思吗?您所做的只是使用 %s 字符串格式。那是如何转义字符串的? psycopg 会自动转义吗?
      • @7alman:是的,你可以阅读psycopg2的这篇文章:initd.org/psycopg/docs/usage.html#query-parameters
      猜你喜欢
      • 1970-01-01
      • 2013-02-22
      • 2019-10-29
      • 1970-01-01
      • 2011-12-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-10
      • 1970-01-01
      相关资源
      最近更新 更多