📜  在Python中使用 SQLAlchemy 连接到 SQL 数据库

📅  最后修改于: 2022-05-13 01:55:43.710000             🧑  作者: Mango

在Python中使用 SQLAlchemy 连接到 SQL 数据库

在本文中,我们将了解如何使用Python中的 SQLAlchemy 连接到 SQL 数据库。

要使用 SQLAlchemy 连接到 SQL 数据库,我们需要在Python环境中安装 sqlalchemy 库。它可以使用 pip 安装 -

$ pip install sqlalchemy

sqlalchemy 库的create_engine()方法接受连接 URL 并返回一个引用方言和池的 sqlalchemy 引擎,它们一起解释 DBAPI 的模块函数以及数据库的行为。

示例 1:对于 MySQL 数据库

在此示例中,我们已成功创建到 MySQL 数据库的连接。请注意,我们在 mySQL 服务器的本地实例中创建了名为“GeekForGeeks”的数据库,密码设置为“password”。与 MySQL 数据库建立连接的方言和驱动程序分别是 MySQL 和 pymysql。

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)


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)


输出:

$ Connection to the 127.0.0.1 for user root created successfully.

示例 2:对于 PostgreSQL 数据库

在此示例中,已与 PostgreSQL 数据库建立了 sqlalchemy 引擎连接。请注意,我们使用了名为“postgres”的预先存在的数据库,该数据库位于 postgresql 服务器的本地实例中。与 MySQL 数据库建立连接的方言和驱动程序是 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)

输出:

$ Connection to the 127.0.0.1 for user root created successfully.