SQLAlchemy allows us to define the database schema using Python classes, simplifying creating tables and specifying their structure. In this Answer, we will discuss creating a database table with SQLAlchemy.
Here’s a step-by-step guide to creating database tables with SQLAlchemy.
We import SQLAlchemy and create a base class using declarative_base()
function. This base class serves as the foundation for the table classes.
from sqlalchemy import create_engine, Column, Integer, String, MetaData, Tablefrom sqlalchemy.ext.declarative import declarative_base# Define Table ClassesBase = declarative_base()
We create a Python class for the database table. Each class should inherit from the Base
class we defined earlier. In the class, we define attributes corresponding to the table’s columns using SQLAlchemy’s column types.
class CustomTable1(Base):__tablename__ = 'Educative_Answers'custom_id = Column(Integer, primary_key=True)custom_name = Column(String, unique=True)
In this example, we’ve defined a Educative_Answers
table with columns for id
and name
. We can adjust the table structure according to our specific requirements.
Now, we need to establish a connection to the database system using the create_engine()
function of SQLAlchemy to create the database and tables, as shown below:
# Replace 'your_database_url_here' with your actual database URLengine = create_engine('your_database_url_here')# Create the tables in the databaseBase.metadata.create_all(engine)
Be sure to replace 'your_database_url_here'
with the appropriate connection details for your database system (e.g., SQLite, PostgreSQL, MySQL).
Now that the tables are created, we can interact with them using SQLAlchemy. We use the simple metadata.tables.keys()
method to print all the tables in our database.
# Create the tables in the in-memory databaseBase.metadata.create_all(engine)# Print the names of all tables in the databasedef print_all_tables(engine):# To load metdata and existing database schemametadata = MetaData()metadata.reflect(bind=engine)tables = metadata.tables.keys()print("List of tables:")for table in tables:print(table)# Print all tables in the in-memory databaseprint_all_tables(engine)
The complete working code is given below. You can alter the code to explore the properties of SQLAlchemy and see the changes in real time.
from sqlalchemy import create_engine, Column, Integer, String, MetaData, Tablefrom sqlalchemy.ext.declarative import declarative_base# Create an in-memory SQLite database engineengine = create_engine('sqlite:///:memory:')# Define Table ClassesBase = declarative_base()class CustomTable1(Base):__tablename__ = 'Educative_Answers'custom_id = Column(Integer, primary_key=True)custom_name = Column(String, unique=True)class CustomTable2(Base):__tablename__ = 'Educative_CloudLabs'custom_id = Column(Integer, primary_key=True)custom_name = Column(String, unique=True)# Create the tables in the in-memory databaseBase.metadata.create_all(engine)# Print the names of all tables in the databasedef print_all_tables(engine):metadata = MetaData()metadata.reflect(bind=engine)tables = metadata.tables.keys()print("List of tables:")for table in tables:print(table)# Print all tables in the in-memory databaseprint_all_tables(engine)
SQLAlchemy simplifies creating and managing database tables in Python straightforward and intuitive. We can easily create and maintain databases across various database systems by defining the table structures as Python classes. SQLAlchemy’s flexibility and ORM capabilities streamline the process of database table creation, allowing us to focus on building the application’s functionality.
Unlock your potential: SQLAlchemy fundamentals series, all in one place!
To deepen your understanding of SQLAlchemy, explore our series of Answers below:
What is SQLAlchemy?
Understand SQLAlchemy’s role in Python database management, offering ORM, SQL expressions, and efficient data handling.
How to connect with a database in SQLAlchemy
Learn how to establish a connection with different databases using SQLAlchemy’s engine and session.
How to create a table in SQLAlchemy
Discover how to define and create database tables using SQLAlchemy’s ORM and core functionalities.
How to execute queries in SQLAlchemy
Explore how to perform CRUD operations efficiently using SQLAlchemy’s query execution methods.
How to use relationships and associations in SQLAlchemy?
Master the implementation of table relationships and associations for structured data modeling.
Free Resources