![]() |
VOOZH | about |
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.
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
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:
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.
Output
Connection to the 127.0.0.1 for user root created successfully.
Explanation:
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.
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.
Output
Connection to the 127.0.0.1 for user root created successfully.
Explanation: