📅  最后修改于: 2023-12-03 15:20:18.066000             🧑  作者: Mango
SQLAlchemy is a popular Python library for working with relational databases. It provides a flexible and easy-to-use API to interact with various database backends. One of the key features of SQLAlchemy is the ability to connect to a database using a database URI.
The database URI is a string that contains all the information needed to connect to a database. This includes the database type, username, password, host, port, and database name.
The syntax of the database URI depends on the type of database you are connecting to. Here are some examples:
postgresql://username:password@host:port/database
mysql://username:password@host:port/database
sqlite:///absolute/path/to/database
Once you have constructed the database URI, you can use it to create an instance of the SQLAlchemy engine
object.
from sqlalchemy import create_engine
# Replace with your database URI
database_uri = "postgresql://username:password@host:port/database"
# Create engine object
engine = create_engine(database_uri)
You can then use the engine
object to interact with the database using SQLAlchemy.
from sqlalchemy import select, text
# Execute a simple select query
with engine.connect() as conn:
result = conn.execute(select("1"))
print(result.fetchone())
# Execute a query using raw SQL
with engine.connect() as conn:
result = conn.execute(text("SELECT * FROM my_table"))
print(result.fetchall())
Using a database URI with SQLAlchemy is a convenient way to connect to a database. It provides a standardized syntax for specifying database connection information, making it easier to switch between different database types. With the SQLAlchemy engine object, you can easily execute SQL queries and interact with the database in a Pythonic way.