psycopg2使用占位符从元组设置PRIMARY KEY

时间:2016-05-28 10:26:07

标签: python psycopg2

如何从元组中循环的元组中设置psycopg2中的主键?

例如我有我的元组

meetattrs = ('id', 'venue', 'date', 'rail', 'weather', 'trackcondition')

然后我想创建表并提取和插入值。从meetattrs我希望将id设置为主键。

conn = psycopg2.connect("")
with conn, conn.cursor() as cur:
        # First, create tables.
    cur.execute("drop table if exists meetings, races, horses")
    cur.execute("create table meetings (id integer PRIMARY KEY, " +
                ", ".join("%s varchar" % fld for fld in meetattrs)
                + ")")

然而,这会产生此错误,不确定如何解决。

Traceback (most recent call last):
  File "racemeeting.py", line 56, in <module>
    + ")")
psycopg2.ProgrammingError: column "id" specified more than once

2 个答案:

答案 0 :(得分:1)

在这种问题中,您应该首先尝试构建和控制sql字符串。

("create table meetings (id integer PRIMARY KEY, " +
            ", ".join("%s varchar" % fld for fld in meetattrs)
            + ")")

给出:

'create table meetings (id integer PRIMARY KEY, id varchar, venue varchar, date varchar, rail varchar, weather varchar, trackconditionvarchar)'

有效地复制id列。

解决方案很简单:从meetattrs删除第一个标识符:

cur.execute("create table meetings (id integer PRIMARY KEY, " +
            ", ".join("%s varchar" % fld for fld in meetattrs[1:])
            + ")")

或者,如果你不能确定主键是否为第一个元素:

cur.execute("create table meetings (id integer PRIMARY KEY, " +
            ", ".join("%s varchar" % fld for fld in meetattrs if fld != 'id')
            + ")")

答案 1 :(得分:1)

在执行join并且占位符获取其值后,您当前的SQL查询是:

'create table meetings (id integer PRIMARY KEY, id varchar, venue varchar, date varchar, rail varchar, weather varchar, trackcondition varchar)'

id指定了两次。

您可以更清晰地构建查询:

query_params = " %s integer PRIMARY KEY" + ", %s varchar" * (len(meetattrs) - 1)

您的SQL语句变为:

"create table meetings (" + query_params % meetattrs + ")"

插入占位符值后:

'create table meetings (id integer PRIMARY KEY, venue varchar, date varchar, rail varchar, weather varchar, trackcondition varchar)'

确保您的元组的第一项始终为id