from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from sqlalchemy.exc import SQLAlchemyError engine = create_engine('postgresql://user:pass@host:port/dbname') Session = sessionmaker(bind=engine) session = Session() try: # some database changes session.commit() except SQLAlchemyError: # if error occurs, rollback changes made to database session.rollback() raise finally: # close database connection session.close()
import sqlite3 conn = sqlite3.connect('example.db') cursor = conn.cursor() try: # some database changes conn.commit() except sqlite3.Error: # if error occurs, rollback changes made to database conn.rollback() raise finally: # close database connection conn.close()In both examples, the code first establishes a connection to the database and creates a session/cursor. Then, some changes are made to the database inside a try block. If an exception occurs while making changes, the session/cursor is rolled back to undo all the changes made in that session. Finally, the database connection is closed. The package library used in the examples depends on the type of database being used. SQLAlchemy is commonly used with relational databases like MySQL, Postgres, and SQLite. The sqlite3 package is used specifically for SQLite databases.