[python]SQLAlchemy usage example

This is an aggregation on how to use SQLAlchemy to create a database, table and insert data into the created table. Refer to this tutorial on how to use SQLAlchemy.

from sqlalchemy_utils import database_exists, create_database
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

url = "mysql+pymysql://username:password@database_address/database_name"

# Create engine object to manipulate the database operation
engine = create_engine(url, echo=True)

# This base object is used to create the table.
Base = declarative_base()

if not database_exists(engine.url):

# Table format
class Remediation(Base):
    __tablename__ = "remediation"
    tid = Column(String(10), primary_key=True)
    sid = Column(Integer, nullable=False)
    uuid = Column(String(255), nullable=False)
    action = Column(String(50), nullable=False)

# Create table

# Insert record
record1 = Remediation(

record2 = Remediation(

# Create database session to update and commit the records.
Session = sessionmaker(bind=engine)
session = Session()
    record1, record2

The sqlalchemy-utils contains two functions that help to create database if not exists.

The create_engine method is used to create a database engine object with the specified database url. The database url is in this format: database_dialect+database_driver://username:password@database_fqdn_or_address/database_name. The database driver is a python package based on the database you are using, for this example I am using MySQL/Mariadb hence the driver is pymysql. The database dialect is the type of database such as Oracle, mysql, postgresql, sqlite3.

The Column method creates a column of a table, the Integer and String methods define the database data type, you need to define the length of String else there is an exception, this is because mysql requires VARCHAR to define the length.

The declarative_base constructor constructs a class object which is inherited by the class that defines the structure of the table.

The sessionmaker constructor creates a session class which creates a session object, this session is required for doing read, update and delete and finally session is used to commit the changes.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s