Column Name as Variable in PostgreSql Query
i was trying to update a table row by row in postgresql using python.
the code used was
cursor.execute("UPDATE im_entry.pr_table
SET selected_entry = im_entry.usr_table.",entryn,"
FROM im_entry.usr_table
WHERE im_entry.pr_table.image_1d = ",idn,"")
...where entryn
and idn
are two string variables ( entry1,entry2.. id1,id2..etc)
I am getting an error
TypeError: function takes at most 3 arguments (5 given)
My table is
image_1d | entry1 | entry2 | entry3 | entry4 | entry5
----------+--------+--------+--------+--------+--------
How can I s开发者_开发技巧olve this?
Try:
cursor.execute(
'''UPDATE im_entry.pr_table
SET selected_entry = im_entry.usr_table.{0}
FROM im_entry.usr_table
WHERE im_entry.pr_table.image_1d = ?'''.format(entryn),[idn])
Normally, you would want to call cursor.execute(sql,args)
, where sql
is a parametrized sql query, and args
is a list or tuple of values to be substituted for the parameter placeholders.
For Postgresql, the usual db driver, pyscopg, uses question marks for the parameter placeholders.
Thus, usually, you'd want to use something like
sql='''UPDATE im_entry.pr_table
SET selected_entry = ?
FROM im_entry.usr_table
WHERE im_entry.pr_table.image_1d = ?'''
but in your case, you aren't trying to set selected_entry
to a specific value, but rather to a column name. Is that correct? In that case, you unfortunately can't use a parameter placeholder. Instead, you have to use string formatting, which is what I suggested above.
You can't bind table or column names, only the values associated with them.
精彩评论