If don't want to have to commit each entry to the database, you can add the following line:

conn.autocommit = True

So your resulting code would be:

import psycopg2

try:
    conn = psycopg2.connect("dbname='djangostack' user='bitnami' host='localhost' password='password'")
    conn.autocommit = True
except:
    print "Cannot connect to db"

cur = conn.cursor()

try:
    cur.execute("""insert into cnet values ('r', 's', 'e', 'c', 'w', 's', 'i', 'd', 't')""")
except:
    print "Cannot insert"
Answer from aright on Stack Overflow
๐ŸŒ
Psycopg
psycopg.org โ€บ docs โ€บ connection.html
The connection class โ€” Psycopg 2.9.12 documentation
Note that a context wraps a transaction: if the context exits with success the transaction is committed, if it exits with an exception the transaction is rolled back. Note that the connection is not closed by the context and it can be used for several contexts. conn = psycopg2.connect(DSN) with conn: with conn.cursor() as curs: curs.execute(SQL1) with conn: with conn.cursor() as curs: curs.execute(SQL2) # leaving contexts doesn't close the connection conn.close()
๐ŸŒ
Psycopg
psycopg.org โ€บ docs โ€บ usage.html
Basic module usage โ€” Psycopg 2.9.12 documentation
If any of the condition is not met several lobject methods will fail if the arguments exceed 2GB. Added in version 2.3. Psycopg exposes the two-phase commit features available since PostgreSQL 8.1 implementing the two-phase commit extensions proposed by the DB API 2.0.
Discussions

Python psycopg2 not inserting into postgresql table - Stack Overflow
Do I need a commit or something? I'm using the postgresql database that was installed with the Bitnami djangostack install. import psycopg2 try: conn = psycopg2.connect("dbname='djangostack' user='bitnami' host='localhost' password='password'") except: print "Cannot connect to db" cur = ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Allow to start transactions in autocommit mode
Hi, using autocommit mode can be quite useful for some long running applications, to make it less likely that transactions are accidentally left open, and to perform operations like VACUUM etc. psy... More on github.com
๐ŸŒ github.com
15
July 2, 2019
With psycopg2 and PostrgeSQL, is it faster to commit changes line by line, or is it faster to iterate across the data with an UPDATE or INSERT INTO command and commit only once the loop reaches the end?
Specifically with postgres, there's also a COPY feature that allows you to load CSV files into tables insanely quickly compared to actual insert operations. Something to think about if insert speed becomes a bottleneck because inserts can't really be parallelized at all More on reddit.com
๐ŸŒ r/learnpython
7
7
October 25, 2018
Are transactions in PostgreSQL via `psycopg2` per-cursor or per-connection? - Database Administrators Stack Exchange
The documentation does not touch on this, though the fact that you can call connection.commit() makes me fairly confident the transaction-control is per-connection. ... Transactions are per-session, i.e. per-connection. PostgreSQL doesn't support suspending and resuming transactions, so psycopg2 ... More on dba.stackexchange.com
๐ŸŒ dba.stackexchange.com
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ enable-autocommit-in-psycopg2-using-python
Enable Autocommit in psycopg2 using Python - GeeksforGeeks
July 23, 2025 - By default, psycopg2 runs in "manual commit" mode, whereby all changes made during a transaction are not saved in the database until explicitly called by using the commit() method.
๐ŸŒ
PostgreSQL Tutorial
postgresqltutorial.com โ€บ postgresql-python โ€บ transaction
PostgreSQL Python: Managing Transactions
January 29, 2024 - 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.
๐ŸŒ
Neon
neon.com โ€บ postgresql โ€บ postgresql-python โ€บ transaction
PostgreSQL Python: Managing Transactions
January 29, 2024 - 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.
๐ŸŒ
PYnative
pynative.com โ€บ home โ€บ python โ€บ databases โ€บ python postgresql transaction management using commit and rollback
Python PostgreSQL Transaction management using Commit and Rollback
March 9, 2021 - How to manage PostgreSQL transaction from Python using psycopg2. How to use auto-commit, commit and rollback to manage transaction. Change PostgreSQL transaction isolation level.
๐ŸŒ
GitHub
github.com โ€บ psycopg โ€บ psycopg2 โ€บ commits
Commits ยท psycopg/psycopg2
PostgreSQL database adapter for the Python programming language - Commits ยท psycopg/psycopg2
Author ย  psycopg
Find elsewhere
๐ŸŒ
GitHub
github.com โ€บ psycopg โ€บ psycopg2 โ€บ issues โ€บ 941
Allow to start transactions in autocommit mode ยท Issue #941 ยท psycopg/psycopg2
July 2, 2019 - Just start a transaction using .execute() - but that breaks con.commit(), because: https://github.com/psycopg/psycopg2/blob/master/psycopg/pqpath.c#L396 ยท
Author ย  psycopg
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python-postgresql-transaction-management-using-commit-and-rollback
Python PostgreSQL - Transaction management using Commit and Rollback - GeeksforGeeks
October 25, 2022 - The commit() function is used to permanently commit all changes to the PostgreSQL database. You may also use the rollback() function to undo any modifications you've made. ... The following is an example of how to handle a transaction in psycopg, ...
๐ŸŒ
Psycopg
psycopg.org โ€บ psycopg3 โ€บ docs โ€บ basic โ€บ transactions.html
Transactions management - psycopg 3.3.5.dev1 documentation
psycopg2.errors.SerializationFailure: ... caused the exception. Added in version 3.1. Psycopg exposes the two-phase commit features available in PostgreSQL implementing the two-phase commit extensions proposed by the DBAPI....
๐ŸŒ
Libelli
bbengfort.github.io โ€บ posts โ€บ transaction handling with psycopg2
Transaction Handling with Psycopg2 | Libelli
December 6, 2017 - Transactions are therefore connection specific. When you create a connection, you can create multiple cursors, the transaction begins when the first cursor issues an execute โ€“ all all commands executed by all cursors after that are part of the same transaction until commit or rollback.
๐ŸŒ
ZetCode
zetcode.com โ€บ python โ€บ psycopg2
Python PostgreSQL proramming with psycopg2 module
January 29, 2024 - The documentation to the psycopg2 module says that the connection is responsible to terminate its transaction, calling either the commit or rollback method. The committed changes are immediately made persistent into the database.
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ with psycopg2 and postrgesql, is it faster to commit changes line by line, or is it faster to iterate across the data with an update or insert into command and commit only once the loop reaches the end?
r/learnpython on Reddit: With psycopg2 and PostrgeSQL, is it faster to commit changes line by line, or is it faster to iterate across the data with an UPDATE or INSERT INTO command and commit only once the loop reaches the end?
October 25, 2018 -

I have a webapp that I built a few months ago that uses a pandas dataframe and stores all data in the memory of the server, does some operations and presents the data. Obviously this is pretty bad design, so I am converting some of the functionality of the app from dataframes in memory to permanent storage in a database using PostgreSQL. My only SQL experience with python up until now was with SQLite which didn't require me to commit changes to the database if to avoid race conditions (not that this matters, as the database is only accessed by functions of the application that I can execute).

So my question is, is it faster to iterate through my data, inserting or updating the database and then committing each line? Or is it faster/possible to perform all the execute commands and then commit only when the loop reaches the end?

I would try both of them, but I don't want to have to clear the database and drop all the tables multiple times as I try it out.

๐ŸŒ
Medium
medium.com โ€บ @SaijyotiTripathy โ€บ python-postgresql-with-psycopg2-tutorial-ee3c31d80e08
Python PostgreSQL with psycopg2 tutorial | by Saijyoti Tripathy | Medium
January 31, 2025 - conn.autocommit=True: By default, psycopg2 works in manual commit mode. This means any changes we make (like inserting or updating data) wonโ€™t be saved until we explicitly use commit() to save them.
๐ŸŒ
Python Forum
python-forum.io โ€บ thread-35185.html
How psycopg2 autocommit works ?
Hi, I'm working on a 'simple' script that makes use of psycopg2. The script takes some time to finish (not the problem), while I was trying to do some optimizations, I discovered that my queries were marked as 'idle' in the pg_stat_activity table. ...
Top answer
1 of 2
9

Transactions are per-session, i.e. per-connection.

PostgreSQL doesn't support suspending and resuming transactions, so psycopg2 couldn't make them per-cursor unless it implicitly created new connections behind the scenes.

In practice I don't find psycopg2's cursors particularly useful. They can retain result sets if you're not using incremental fetch from the server, but I don't find them good for much else.

Why manually issue begin and commit though, rather than using the connection methods for them?

2 of 2
3

From the psycopg2 documentation:

In Psycopg transactions are handled by the connection class. By default, the first time a command is sent to the database (using one of the cursors created by the connection), a new transaction is created. The following database commands will be executed in the context of the same transaction โ€“ not only the commands issued by the first cursor, but the ones issued by all the cursors created by the same connection. Should any command fail, the transaction will be aborted and no further command will be executed until a call to the rollback() method.

At the same time, from version 2.4.2, there is the autocommit attribute (emphasis added):

Read/write attribute: if True, no transaction is handled by the driver and every statement sent to the backend has immediate effect; if False a new transaction is started at the first command execution: the methods commit() or rollback() must be manually invoked to terminate the transaction.

The autocommit mode is useful to execute commands requiring to be run outside a transaction, such as CREATE DATABASE or VACUUM.

The default is False (manual commit) as per DBAPI specification.

๐ŸŒ
PostgreSQL Wiki
wiki.postgresql.org โ€บ wiki โ€บ Psycopg2_Tutorial
Psycopg2 Tutorial - PostgreSQL wiki
See PostgreSQL docs, and keep this in mind when using Python context managers, which handle session transaction COMMIT and ROLLBACK. In order to complete data catalog operations, the AUTOCOMMIT setting allows for commands to be submitted accordingly. #!/usr/bin/env python # # Small script to show Pyscopg2 cursor # import psycopg2 conn = psycopg2.connect("dbname='template1' user='dbuser' host='localhost' password='dbpass'") print(f"Autocommit: {conn.autocommit} and Isolation Level: {conn.isolation_level}") # change the behavior of commit conn.autocommit = True print(f"Autocommit: {conn.autocomm
๐ŸŒ
pythontutorials
pythontutorials.net โ€บ blog โ€บ how-do-i-do-database-transactions-with-psycopg2-python-db-api
How Do Database Transactions Work in psycopg2 (Python)? No .begin() Method? Guide to Commit, Rollback & Isolation Levels โ€” pythontutorials.net
Durability: Once committed, changes are permanent (even if the database crashes). ... 100 from Account A to Account B: if the update to Account B fails after deducting 100fromAccountAtoAccountB:iftheupdatetoAccountBfailsafterdeducting100 from Account A, Account A would be short $100 with no corresponding credit to Account B. Transactions prevent this. Unlike some ORMs or database drivers (e.g., JDBC), psycopg2 does not require an explicit begin() method to start a transaction.
๐ŸŒ
DeepWiki
deepwiki.com โ€บ psycopg โ€บ psycopg2 โ€บ 4.4-transaction-management
Transaction Management | psycopg/psycopg2 | DeepWiki
April 29, 2025 - In psycopg2, a database connection starts a new transaction the first time a command is executed. The transaction remains active until explicitly committed or rolled back.