def update_database(self, results):
try:
length = len(self.unique_ids)
update_data = [(self.unique_ids[i], results[i]) for i in range(length)]
query = """
UPDATE public.post_data AS p
SET content = t.content
FROM (VALUES %s)
AS t (unique_id, content)
WHERE p.unique_id = t.unique_id;
"""
template = '(%s, %s)'
execute_values(self.cursor, query, update_data, template=template)
self.conn.commit()
logging.info("Successfully Updated")
except Exception as error:
logging.warning(f"Update Error -> {error}")
finally:
self.conn.close()
self.cursor.close()
This is the code i execute for bulk update. When i run the query separately in query console it works just fine, doesn’t properly work this way though.
2
Answers
Change
self.cursor
toself.conn.cursor()
.Even better, use
with
to ensure the connection is closed after the transaction.like:
Thank you so much for your answer, unfortunately it didn’t work. On the other hand i have realized another interesting point here. When i try to run this:
It doesn’t make any change in database at all. What can be causing it? Note: The table and columns indeed exist.