1
Today I am using the following code to call via API and store my data in the Postgresql database:
conn = psycopg2.connect("dbname='DBNAME' user='USER' host='HOST'
password='PASSWORD'")
insert = "INSERT INTO TABLE (COLUMN1,COLUMN2,COLUMN3,COLUMN4,COLUMN5)
VALUES"
.... Here is a list where I extract the data in json and insert it into the database .....
if len(gravar) >0 :
cur = conn.cursor()
y = b','.join(cur.mogrify("
(%s,%s,%s,%s,%s)", x) for x in gravar)
comando = insert + y.decode()
try:
cur.execute("TRUNCATE TABLE TABLE")
cur.execute(comando)
conn.commit()
except (Exception, psycopg2.DatabaseError) as error:
print(error)
cur.close()
print('Carga Completa')
else:
conn.close()
print('Nada a Inserir')
To not overwrite the data I am doing a trucate before running Insert. How I could do an "Insert or update" in this command, thus avoiding having to truncate the table?
What version of yours
PostgreSQL
?– Sorack
Perhaps the usual ON CONFLICT DO UPDATE can help you. https://www.postgresql.org/docs/current/sql-insert.html
– anonimo
As mentioned you can use the
INSERT
with theON CONFLICT
. There are some observations: postgres must be version >=9.5; theON CONFLICT
validates the restriction corresponding to only one field or Constraint.– Camilo Santos
@Camilosantos Thanks a lot for the help, I put the ON CONFLICT is worked normally!
– Maursb
Cool @Maursb!! As a suggestion, post your solution in the answer to the question. That way if someone else is in the same situation you can use your solution.
– Camilo Santos