How to Use SQLAlchemy Core with SQLite in Python
Writing plain SQL queries in Python code is a bit of a hazard. The solution to the problem is ORM(Object Relational Mapping).ORMs help you work with the database in a more Pythonic way.
SQLAlchemy is one of the famous ORMs for relational databases. SQLAlchemy is a vast SQL toolkit with lots of different components. The two large components are SQLAlchemy Core and SQLAlchemy ORM.
SQLAlchemy core has a schema centric view while SQLAlchemy ORM uses an Object Centric View.
Use SQLAlchemy Core with SQLite in Python
In this example, we will use the SQLAlchemy core, which differs in SQL itself.
Step 1: Install SQLAlchemy
To use SQLAlchemy in Python, first, we need to install it. Please type the following command to install it.
python3 -m pip install sqlalchemy
Step 2: Import SQLAlchemy
Now import in your project using the Python import statement.
# app.py import sqlalchemy as db
As you can see that we imported sqlalchemy as db.
Now, I have already created a Database called shows.db in my project folder but if you don’t know how to create it, then check out how to create an SQLite database in Python.
Now in that database, I have created a table called shows with some records. We will fetch those records using SQLAlchemy.
Step 3: Connect with the database.
To connect with the database, use the create_engine() function.
The engine allows us to create multiple database connections, and it manages those connections.
engine = db.create_engine('sqlite:///shows.db')
As we have discussed earlier, our database name is
From the engine, we can create a connection and run the database queries.
The next step is to use the connect() function to connect with the database.
connection = engine.connect()
Step 4: Retrieve the Metadata
We can retrieve the metadata about our database with DB.metadata. This metadata will hold all the information about our table.
metadata = db.MetaData()
Step 5: Load the shows table
To load the SQL table, use the db.Table() function. The Table() function takes Shows table, Metadata, autoload=True, and autoload_with=engine.
shows = db.Table('Shows', metadata, autoload=True, autoload_with=engine)
Step 6: Prepare the Query
With our table loaded, let’s prepare a query to select all the records from the shows table. In regular SQL, to select all the records, it is “SELECT * FROM shows”. The SQLAlchemy Core query looks like this.
query = db.select([shows])
We prepared a query, but this does not do anything. We need to execute this query. So first, we need to save the select query into the query variable.
Step 7: Execute the Query
To execute the query, use execute() function. It returns the object that proxies cursor object from the Python Database API.
result_proxy = connection.execute(query)
Now, we use the result_proxy object to retrieve the data.
Step 8: Fetch the data.
To fetch the data from the object, use the fetchall() method.
result_set = result_proxy.fetchall()
And now, print the result_set.
The complete code of this example app.py is the following.
# app.py import sqlalchemy as db engine = db.create_engine('sqlite:///shows.db') connection = engine.connect() metadata = db.MetaData() shows = db.Table('Shows', metadata, autoload=True, autoload_with=engine) query = db.select([shows]) result_proxy = connection.execute(query) result_set = result_proxy.fetchall() print(result_set)
python3 app.py [('Stranger Things', 'Shawn Levy', 2016), ('Money Heist', 'Alex Rodrigo', 2017), ('Dark', 'Baran bo Odar', 2017), ('1992 Scam', 'Hansal Mehta', 2020)]
As you can see that we get all the records from the shows table. It returns the list of tuples containing our records.
We can also select the specific rows because it returns the list, and we can use the index to get the specific list data.
# app.py print(result_set) print(result_set[:2])
('Money Heist', 'Alex Rodrigo', 2017) [('Stranger Things', 'Shawn Levy', 2016), ('Money Heist', 'Alex Rodrigo', 2017)]
That is it for SQLAlchemy Core with SQLite in Python.