且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

更新冲突 postgres 上的多列

更新时间:2023-01-31 09:58:53

对您问题的直接回答是,您执行 tuple + tuple 以将元组加倍.

The direct answer to your question is, you do a tuple + tuple to double the tuple.

cursor.execute(upsert_query, data_tuple + data_tuple)

其他选项:

如果你有单独的值并且你正在构造元组,你可以直接构造一个具有两倍值数量的元组.

Other Options:

If you have individual values and you are constructing the tuple, you can directly construct a tuple with twice the number of values.

query="""INSERT INTO table (col1,col2,col3,col4,col5,col6,col7,col8,col9,..col20) VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)
ON CONFLICT(col2) DO UPDATE SET col1=%s, col3=%s, col4=%s, ..."""

cur.execute(query, (c1, c2, c3, ... c20, c1, c3, c4, ... c20))

您必须指定值(col2 除外)两次.

You will have to specify the values (except col2) twice.

如果您已经有了最初要求的元组,那么您将使用 + 将同一个元组合并两次.

If you already have the tuple, which is what you originally asked, then you will use a + to merge the same tuple twice.

如果您有单个值而不是元组,您还可以使用命名参数,如字典.

If you have the individual values and not the tuple, you could also use named parameters like a dictionary.

query="""INSERT INTO table (col1,col2,col3,col4...) VALUES(%(c1)s, %(c2)s, %(c3)s, %(c4)s...) ON CONFLICT(col2) DO UPDATE SET col1=%(c1)s, col3=%(c3)s, col4=%(c4)s, ..."""
cur.execute(query, {'c1': c1val, 'c2': c2val, 'c3': c3val, 'c4': c4val, ...})

这种形式有利于可读性,只传递一次参数,如果以后的列数发生变化,易于维护(增加列数等).

This form is good for readability, passes parameters only once, and is easy to maintain (increase in columns, etc) if the number of columns change in the future.