I have a table with columns as below: (id, col1, col2, col3, col4)
. I need to insert new row to this table, with given data is a dict: data = {'id': 1, 'col1': 1, 'col2':1, 'col3':1, 'col4': 1}
for example.
I want to use the query below to insert data into table if id not existed, or update the table if id existed:
query =
'''
INSERT INTO tablename (id, col1, col2, col3, col4)
VALUES (%(id)s, %(col1)s, %(col2)s, %(col3)s, %(col4)s)
ON CONFLICT (id) DO UPDATE SET
col2 = col2 + 1;
'''
result = cur.execute(query, data)
I can pass data into the Insert block, but with the On Conflict block when do the updating, col2 = col2 + data['col2] it raised the error as column referance "col2" is ambiguous
.
Another question is how to update col2 value based on condition from other columns, for example:
col2 = col2 + 1 if col1 == data['col1] else col2 = col2