Es gibt mehrere Möglichkeiten das commit oder rollback über Context-Blöcke zu steuern
with psycopg.connect(someconnectionninformation) as connection: cursor = connection.cursor() cursor.execute(somestatement) cursor.execute(someotherstatement)
Außerdem wird die Verbindung zur Datenbank danach geschlossen
with psycopg.connect(someconnectionninformation) as connection: cursor = connection.cursor() with connection.transaction(): cursor.execute(somestament) cursor.execute(somestament) with connection.transaction(): cursor.execute(somestament) cursor.execute(somestament)
Man muss allerdings aufpassen, wenn außerhalb der transaction-Blöcke Statements ausgeführt werden, dann starten diese implizit Transaktionen und die transaction-Blöcke erstellen dann nur savepoint sub-transactions.
Ggf. sollte man beim connect dann autocommit=True setzen, dann werden alle Statements außerhalb der transaction-Blöcke als eigene Transaktionen gehandhabt, die sofort commited sind.
conn.execute(insert into whatever values(%s); select * from somethingelse where id = %s, ("firstvalue", "secondvalue"))
create temp table somename (somerow varchar) on commit delete rows;
Daten in eine Tabelle einfügen:
with cursor.copy("copy table_name (column1, column2) from stdin") as copy: for record in records: copy.write_row(record)
Daten aus einer Tabelle auslesen:
with cursor.copy("copy table_name (column1, column2) to stdout") as copy: for record in copy.rows(): Some action
Traceback (most recent call last): File "mytest.py", line 24, in <module> copy.write_row(word) File "/usr/lib/python3.8/contextlib.py", line 120, in __exit__ next(self.gen) File "usr/share/virtualenvs/noise3-IfVx2oqf/lib/python3.8/site-packages/psycopg/cursor.py", line 902, in copy raise ex.with_traceback(None) psycopg.errors.BadCopyFileFormat: extra data after last expected column CONTEXT: COPY personen, line 1: "H a n s"
Daher wurde „Getting“ nicht als String, sondern als Sequenz betrachtet und versucht in mehr Spalten einzufügen als vorhanden sind.
Fehlschlagender Code (Beispiel):
names = ["Hans", "Peter", "Dieter"] with cursor.copy("copy personen (vorname) from stdin") as copy: for name in names: copy.write_row(name)
Hier sollte man auch aufpassen:
names = ["Hans", "Peter", "Dieter"] with cursor.copy("copy personen (vorname) from stdin") as copy: for name in names: copy.write_row((name))