PostgreSQL Python: Transactions
Summary: in this tutorial, you will learn how to handle PostgreSQL transactions in Python.
This tutorial picks up from where the Updating Data in a Table Tutorial left off.
Introduction to transactions in Python
In the psycopg2
package, the connection
class is responsible for managing transactions.
When you send the first SQL statement to the PostgreSQL database using a cursor
object, psycopg2
initiates a new transaction.
Subsequentially, all the following statements are executed within the same transaction. If any statement encounters an error, psycopg2
will abort the entire transaction.
The connection
class has two methods for concluding a transaction:
commit()
– Use this method to permanently apply all changes to the PostgreSQL database.rollback()
– Call this method to discard the changes.
Closing a connection object by calling the close() method or deleting it using del
will also trigger an implicit rollback:
Or
Alternatively, you can set the autocommit
attribute of the connection
object to True
. This ensures that psycopg2
executes every statement and commits it immediately.
The autocommit
mode can be particularly useful when executing statements that need to operate outside a transaction, such as CREATE DATABASE and VACUUM
.
The following shows a typical pattern for managing a transaction in psycopg2
:
Managing transactions using context managers
Starting from psycopg
2.5, the connection and cursor are context managers therefore you can use them in the with
statement:
The psycopg2
commits the transaction if no exception occurs within the with
block, otherwise, it rolls back the transaction.
Unlike other context manager objects, exiting the with
block does not close the connection but only terminates the transaction. Consequentially, you can use the same connection
object in the subsequent with
statements in another transaction as follows:
PostgreSQL transaction example
We will use the parts
and vendor_parts
tables in the suppliers
database:
Suppose you need to add a new part and assign the vendors who supply the part at the same time.
To achieve this, you can do as follows:
- First, insert a new row into the
parts
table and get the part id. - Then, insert rows into the
vendor_parts
table.
The following add_part()
function demonstrates the steps:
2) Execute the transaction.py module
First, open the Command Prompt on Windows or Terminal on Unix-like systems.
Second, run the following command to execute the transaction.py
module:
3) Verify transaction
First, connect to the suppliers
on the PostgreSQL server:
Second, retrieve data from the parts
table:
Output:
Third, query data from the vendor_parts
table:
Output:
4) Test a failed transaction
Let’s insert another part, but this time, we intentionally use an invalid vendor id for demonstration purposes.
The program should not add a new part without assigning it to a vendor.
An exception occurred.
You can query data from the parts
and vendor_parts
tables again. There will be no new data, meaning that the program works as expected.
Download the project source code
Summary
- Use the
commit()
method to permanently apply all changes to the database. - Use the
rollback()
method to discard the changes.