GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Python Tutorial
  • Data Types
  • Interview Questions
  • Examples
  • Quizzes
  • DSA Python
  • Data Science
  • NumPy
  • Pandas
  • Practice
  • Django
  • Flask
  • Introduction1 min read
  • Input & Output2 min read

This view

  • Original page
  • New address

GeezerVison is showing www.geeksforgeeks.org — Connecting to SQL Database using SQLAlchemy in Python - GeeksforGeeks

geeksforgeeks
search icon
  • Courses
  • Tutorials
  • Interview Prep
  • Python Tutorial
  • Data Types
  • Interview Questions
  • Examples
  • Quizzes
  • DSA Python
  • Data Science
  • NumPy
  • Pandas
  • Practice
  • Django
  • Flask

Connecting to SQL Database using SQLAlchemy in Python

Last Updated : 16 Mar, 2026

SQL databases can be connected in Python by creating a database engine using SQLAlchemy. The connection is defined through a URL that includes the database type, credentials, host, port and database name. Using this method, connections can be established with databases such as MySQL and PostgreSQL.

Installation

Before creating a database connection, SQLAlchemy package must be installed in the Python environment. If not installed, install it using below command:

pip install sqlalchemy

Creating a Database Connection

SQLAlchemy creates database connections using create_engine() function. This function takes a connection URL and returns an engine object, which manages the connection between Python and the database.

Syntax:

sqlalchemy.create_engine(url, **kwargs)

URL Format: dialect+driver://username:password@host:port/database

Components:

  • dialect: database type (mysql, postgresql, sqlite)
  • driver: database connector library (pymysql, psycopg2)
  • username/password: login credentials
  • host/port: database server location
  • database: database name

Connecting to MySQL Database

The following example demonstrates how to create a connection to a MySQL database using SQLAlchemy. The code defines database credentials, creates a connection URL and generates an engine object that represents the connection.

Python
from sqlalchemy import create_engine

user = "root"
password = "password"
host = "127.0.0.1"
port = 3306
database = "GeeksForGeeks"

def get_connection():
    engine = create_engine(
        f"mysql+pymysql://{user}:{password}@{host}:{port}/{database}"
    )
    return engine

if __name__ == "__main__":

    try:
        engine = get_connection()
        print(f"Connection to the {host} for user {user} created successfully.")

    except Exception as ex:
        print("Connection could not be made due to the following error:\n", ex)

Output

Connection to the 127.0.0.1 for user root created successfully.

Explanation:

  • user, password, host, port, database: Stores the MySQL database credentials and server details required to create the connection.
  • def get_connection(): Defines a function that will create and return the database engine.
  • create_engine(f"mysql+pymysql://{user}:{password}@{host}:{port}/{database}"): creates the SQLAlchemy engine using the MySQL dialect and pymysql driver.
  • engine = get_connection(): calls the function to generate the database connection engine.
  • except Exception as ex: handles errors and prints the reason if the connection fails.

Note: In these examples, database credentials are written directly in the code for simplicity. In production environments, credentials should not be hardcoded and are usually stored securely using environment variables, configuration files, or secret managers.

Connecting to PostgreSQL Database

The next example shows how to connect to a PostgreSQL database using SQLAlchemy. The process is similar to MySQL, but the connection URL uses the PostgreSQL dialect and default PostgreSQL port.

Python
from sqlalchemy import create_engine

user = "root"
password = "password"
host = "127.0.0.1"
port = 5432
database = "postgres"

def get_connection():
    engine = create_engine(
        f"postgresql://{user}:{password}@{host}:{port}/{database}"
    )
    return engine

if __name__ == "__main__":

    try:
        engine = get_connection()
        print(f"Connection to the {host} for user {user} created successfully.")

    except Exception as ex:
        print("Connection could not be made due to the following error:\n", ex)

Output

Connection to the 127.0.0.1 for user root created successfully.

Explanation:

  • def get_connection(): defines a function that will create the PostgreSQL connection engine.
  • create_engine(f"postgresql://{user}:{password}@{host}:{port}/{database}"): creates the SQLAlchemy engine using the PostgreSQL dialect.
  • engine = get_connection(): calls the function to create the database connection.
  • except Exception as ex: catches errors and prints the error message if the connection fails.
Comment

Explore

    Python Fundamentals
    • Introduction1 min read
    • Input & Output2 min read
    • Variables4 min read
    • Operators4 min read
    • Keywords2 min read
    • Data Types4 min read
    • Conditional Statements3 min read
    • Loops3 min read
    • Functions4 min read
    Python Data Structures
    • String4 min read
    • List3 min read
    • Tuples3 min read
    • Dictionary3 min read
    • Set2 min read
    • Arrays5 min read
    Advanced Python
    • OOP Concepts3 min read
    • Exception Handling5 min read
    • File Handling4 min read
    • Python Database2 min read
    • MongoDB3 min read
    • MySQL7 min read
    • Packages4 min read
    • Modules3 min read
    • DSA Libraries5 min read
    • Python GUI2 min read
    Data Science with Python
    • Numpy3 min read
    • Pandas4 min read
    • Matplotlib3 min read
    • Seaborn3 min read
    • StatsModel2 min read
    • Model Building6 min read
    • TensorFlow2 min read
    • PyTorch5 min read
    Web Development with Python
    • Flask3 min read
    • Django5 min read
    • Django ORM4 min read
    • Jinja2 Templating5 min read
    • Django Templates5 min read
    • REST API3 min read
    • Build API with DRF4 min read
    Python Practice
    • Quiz1 min read
    • Practice Problems2 min read
    • Interview Q & A15+ min read
    Courses
    • Placement 360 Course2 min read
    • Data Science 360 Course2 min read
    • AI Engg Course2 min read
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.