python - psycopg2 set PRIMARY KEY from tuple with placeholder -
how can set primary key in psycopg2 tuple of values being looped in tuple?
for example have tuple
meetattrs = ('id', 'venue', 'date', 'rail', 'weather', 'trackcondition')
and want create table , extract , insert values. meetattrs wish set id primary key.
conn = psycopg2.connect("") conn, conn.cursor() 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 fld in meetattrs) + ")")
this creates error, unsure how resolve.
traceback (most recent call last): file "racemeeting.py", line 56, in <module> + ")") psycopg2.programmingerror: column "id" specified more once
your current sql query after join
performed , placeholders take values is:
'create table meetings (id integer primary key, id varchar, venue varchar, date varchar, rail varchar, weather varchar, trackcondition varchar)'
id
specified twice.
you can build query in cleaner way:
query_params = " %s integer primary key" + ", %s varchar" * (len(meetattrs) - 1)
and sql statement becomes:
"create table meetings (" + query_params % meetattrs + ")"
after insertion of placeholder values:
'create table meetings (id integer primary key, venue varchar, date varchar, rail varchar, weather varchar, trackcondition varchar)'
be sure tuple has first item id
Comments
Post a Comment