The Wayback Machine - https://web.archive.org/web/20240604154212/https://www.geeksforgeeks.org/connecting-to-sql-database-using-sqlalchemy-in-python/
Open In App

Connecting to SQL Database using SQLAlchemy in Python

Last Updated : 21 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will see how to connect to an SQL database using SQLAlchemy in Python.

To connect to a SQL database using SQLAlchemy we will require the sqlalchemy library installed in our python environment. It can be installed using pip –

!pip install sqlalchemy

The create_engine() method of sqlalchemy library takes in the connection URL and returns a sqlalchemy engine that references both a Dialect and a Pool, which together interpret the DBAPI’s module functions as well as the behavior of the database.

Syntax: sqlalchemy.create_engine(url, **kwargs)

Parameters:

  • url: str

The connection URL to the database of type “dialect+driver://username:password@host:port/database”.

Example 1: For MySQL Database

In this example,  we have successfully created a connection to the MySQL database. Please note that we have created the database named ‘GeekForGeeks’ in the local instance of mySQL server with the password set as ‘password’. The dialect and driver for establishing the connection to MySQL database are MySQL and pymysql respectively.

Python




# IMPORT THE SQALCHEMY LIBRARY's CREATE_ENGINE METHOD
from sqlalchemy import create_engine
 
# DEFINE THE DATABASE CREDENTIALS
user = 'root'
password = 'password'
host = '127.0.0.1'
port = 3306
database = 'GeeksForGeeks'
 
# PYTHON FUNCTION TO CONNECT TO THE MYSQL DATABASE AND
# RETURN THE SQLACHEMY ENGINE OBJECT
def get_connection():
    return create_engine(
        url="mysql+pymysql://{0}:{1}@{2}:{3}/{4}".format(
            user, password, host, port, database
        )
    )
 
 
if __name__ == '__main__':
 
    try:
       
        # GET THE CONNECTION OBJECT (ENGINE) FOR THE DATABASE
        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.

Example 2: For PostgreSQL Database

In this example, a sqlalchemy engine connection has been established with the PostgreSQL database. Please note that we have used the pre-existing database named ‘postgres’ that comes within the local instance of postgresql server. The dialect and driver for establishing the connection to MySQL database is postgres.

Python




# IMPORT THE SQALCHEMY LIBRARY's CREATE_ENGINE METHOD
from sqlalchemy import create_engine
 
# DEFINE THE DATABASE CREDENTIALS
user = 'root'
password = 'password'
host = '127.0.0.1'
port = 5432
database = 'postgres'
 
# PYTHON FUNCTION TO CONNECT TO THE POSTGRESQL DATABASE AND
# RETURN THE SQLACHEMY ENGINE OBJECT
def get_connection():
    return create_engine(
        url="postgresql://{0}:{1}@{2}:{3}/{4}".format(
            user, password, host, port, database
        )
    )
 
 
if __name__ == '__main__':
 
    try:
        # GET THE CONNECTION OBJECT (ENGINE) FOR THE DATABASE
        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.


Similar Reads

Connecting Pandas to a Database with SQLAlchemy
In this article, we will discuss how to connect pandas to a database and perform database operations using SQLAlchemy. The first step is to establish a connection with your existing database, using the create_engine() function of SQLAlchemy. Syntax: from sqlalchemy import create_engine engine = create_engine(dialect+driver://username:password@host:
3 min read
Connecting PostgreSQL with SQLAlchemy in Python
In this article, we will discuss how to connect PostgreSQL with SQLAlchemy in Python. In order to connect with any Database management system, it is essential to create an engine object, that serves as a central source of connection by providing a connection pool that manages the database connections. This SQLAlchemy engine is a global object which
3 min read
Read SQL database table into a Pandas DataFrame using SQLAlchemy
To read sql table into a DataFrame using only the table name, without executing any query we use read_sql_table() method in Pandas. This function does not support DBAPI connections. read_sql_table()Syntax : pandas.read_sql_table(table_name, con, schema=None, index_col=None, coerce_float=True, parse_dates=None, columns=None, chunksize=None) Paramete
2 min read
PostgreSQL - Connecting to the database using Python
PostgreSQL API for Python allows user to interact with the PostgreSQL database using the psycopg2 module. In this article we will look into the process of connecting to a PostgreSQL database using Python. Prerequisites: First we will need to install the psycopg2 module with the below command in the command prompt: pip install psycopg2 Creating a Da
2 min read
Python SQLite - Connecting to Database
In this article, we'll discuss how to connect to an SQLite Database using the sqlite3 module in Python. Connecting to the Database Connecting to the SQLite Database can be established using the connect() method, passing the name of the database to be accessed as a parameter. If that database does not exist, then it'll be created. sqliteConnection =
2 min read
Create a SQL table from Pandas dataframe using SQLAlchemy
In this article, we will discuss how to create a SQL table from Pandas dataframe using SQLAlchemy. As the first steps establish a connection with your existing database, using the create_engine() function of SQLAlchemy. Syntax: from sqlalchemy import create_engine engine = create_engine(dialect+driver://username:password@host:port/database) Explana
3 min read
How to GroupBy and Sum SQL Columns using SQLAlchemy?
In this article, we are going to see how to use GroupBy and Sum in SQLAlchemy. Installing SQLAlchemySQLAlchemy is available via pip install package. pip install sqlalchemyHowever, if you are using a flask you can make use of its own implementation of SQLAlchemy. It can be installed using - pip install flask-sqlalchemy In the examples, we will make
4 min read
Sqlalchemy Core With Text SQL For Date Range
SQLAlchemy Core is a low-level SQL abstraction layer of SQLAlchemy, a popular Python Object Oriented Mapping(ORM) library. It provides a way to interact with relational databases wing python code, allowing developers to write SQL Queries in a more object-oriented manner. SQLAlchemy is a python library that provides a set of tools for working with d
2 min read
How to execute raw SQL in Flask-SQLAlchemy app
In this article, we are going to see how to execute raw SQL in Flask-SQLAlchemy using Python. Installing requirements Install the Flask and Flask-SQLAlchemy libraries using pip pip install Flask pip install flask_sqlalchemySyntaxTo run raw SQL queries, we first create a flask-SQLAlchemy engine object using which we can connect to the database and e
4 min read
How to Execute Raw SQL in SQLAlchemy
In this article, we will see how to write a Conventional SQL query in SQLAlchemy using text() against a PostgreSQL database in python. Creating table for demonstration Import necessary functions from the SQLAlchemy package. Establish connection with the PostgreSQL database using create_engine() function as shown below, create a table called books w
3 min read
Article Tags :
Practice Tags :