SQLAlchemy and the Database Engine#
In the previous notebook, Working with Databases in Python, we connected to a SQLite database using Python’s built-in sqlite3 module and wrote raw SQL strings to create tables, insert data, and run queries.
That approach is fine for small scripts and quick experiments, but production FinTech systems typically need more:
Support for different database backends (PostgreSQL, MySQL, SQL Server, cloud services).
Connection pooling so high-traffic services can efficiently reuse database connections.
A consistent way to build SQL queries programmatically.
Integration with larger application frameworks.
SQLAlchemy is one of the most widely used database libraries in Python. At its highest level, SQL Alchemy provides an Object Relational Mapper (ORM) that binds Python classes to relational tables. Underneath that layer is the “Core,” which provides an SQL Expression Language to attempt to provide a more Python-oriented way to query databases, and the “Engine,” which forms the gateway to the underlying database:
Encapsulates the database connection details (URL, driver, credentials).
Manages connections and resources efficiently.
Gives us a uniform interface for executing SQL, regardless of the underlying database.
In this notebook, we will:
Create a SQLAlchemy Engine to connect to a database.
Use it to execute raw SQL (similar to what we did with
sqlite3, but more robust).See how this pattern scales to real-world FinTech applications, where services must talk reliably to production-grade relational databases.
We’ll start with the lowest level and then cover the ORM layer.
Connecting to a database#
Generally, to get started connecting to a database, you’ll need to provide a database URI (connection string). For SQL Alchemy, the connect string has the format:
dialect + driver :// user : password @ host :port / dbname
Item |
Description |
|---|---|
dialect |
Database Type |
driver |
Specific driver to connect to the database type. Optional |
user and password |
Database authentication settings if needed |
host |
which server is the database on? |
:port |
which port to connect to? Will default to the vendor’s standard port |
dbname |
which database to initially connect to on the server |
1from sqlalchemy import create_engine
2from sqlalchemy import text
create_engine() is a factory to create database connections. However, it does not actually connect to the database until connect() is called.
1engine = create_engine("sqlite:///data/chinook.db")
2connection = engine.connect()
Executing Queries#
Now, we can run SQL queries on that connection. To execute standard “text” qeueries, we’ll need to use the text object.
1stmt = text('select firstname, lastname from customers order by lastname, firstname')
2result = connection.execute(stmt)
The result object that is returned is a special proxy object that acts as a database cursor to iterate over the rows returned from the query’s execution. The object also provides metadata about the results.
If we are only interested in the first record, we can call first() which returns the first row and closes the result object. This row/record object looks like a standard named tuple for Python:
1first_record = result.first()
2print(first_record)
3print(first_record[0]) # access tuple by position
4print(first_record[1])
5print(first_record._mapping) # provides a dictionary interface
6print(first_record.FirstName) # access tuple by column name. note this is case sensitive
('Roberto', 'Almeida')
Roberto
Almeida
{'FirstName': 'Roberto', 'LastName': 'Almeida'}
Roberto
Note that once a result object is closed, you can no longer call methods on that objcet. Whatever resources have been allocated are freed.
We can also use common, idiomatic Python patterns with the results.
1result = connection.execute(stmt)
2for first, last in result:
3 print("{}, {}".format(last,first))
Almeida, Roberto
Barnett, Julia
Bernard, Camille
Brooks, Michelle
Brown, Robert
Chase, Kathy
Cunningham, Richard
Dubois, Marc
Fernandes, João
Francis, Edward
Girard, Wyatt
Gonçalves, Luís
Gordon, John
Goyer, Tim
Gray, Patrick
Gruber, Astrid
Gutiérrez, Diego
Hansen, Bjørn
Harris, Frank
Holý, Helena
Hughes, Phil
Hämäläinen, Terhi
Johansson, Joakim
Jones, Emma
Kovács, Ladislav
Köhler, Leonie
Leacock, Heather
Lefebvre, Dominique
Mancini, Lucas
Martins, Eduardo
Mercier, Isabelle
Miller, Dan
Mitchell, Aaron
Murray, Steve
Muñoz, Enrique
Nielsen, Kara
O'Reilly, Hugh
Pareek, Manoj
Peeters, Daan
Peterson, Jennifer
Philips, Mark
Ralston, Frank
Ramos, Fernanda
Rocha, Alexandre
Rojas, Luis
Sampaio, Madalena
Schneider, Hannah
Schröder, Niklas
Silk, Martha
Smith, Jack
Srivastava, Puja
Stevens, Victor
Sullivan, Ellie
Taylor, Mark
Tremblay, François
Van der Berg, Johannes
Wichterlová, František
Wójcik, Stanisław
Zimmermann, Fynn
We can also put all of the results into a list.
1result = connection.execute(stmt)
2all_records = result.all() # returns a list of the row/records object
3all_records[1]._mapping # for the second element, retrieve the dictionay interface
{'FirstName': 'Julia', 'LastName': 'Barnett'}
Closing a connection#
Once you have completed your work with the database, you should call close(). This releases the connection back into the connection pool for future use.
Context Manager#
You can also use a context mananger to implicitly close a connection.
1with engine.connect() as connection:
2 result = connection.execute(text("select artists.name, albums.title from artists inner join albums on artists.artistid = albums.artistid"))
3 all_rows = result.all()
4 print(len(all_rows))
347
Transactions#
By default, SQLAlchemy places the connection into a transaction and you will need to explicitly commit the transaction for the change to persist.
1with engine.connect() as connection:
2 result = connection.execute(text("insert into artists (artistid,name) values(99999,'Fintech')"))
3
4with engine.connect() as connection:
5 result = connection.execute(text("select * from artists where artistid=99999"))
6 print(result.first()) # no record available. Transaction was never committed
None
1with engine.connect() as connection:
2 result = connection.execute(text("insert into artists (artistid,name) values(99999,'Fintech')"))
3 connection.commit() # mark the change as successful. Database will commit the change
4
5with engine.connect() as connection:
6 result = connection.execute(text("select * from artists where artistid=99999"))
7 print(result.first())
(99999, 'Fintech')
1# clean up the change (removes the inserted recod)
2with engine.connect() as connection:
3 result = connection.execute(text("delete from artists where artistid=99999"))
4 connection.commit()
You can also use the begin() method in the with clause to automatically commit the transaction
1with engine.begin() as connection:
2 result = connection.execute(text("insert into artists (artistid,name) values(99999,'Fintech')"))
3 # Transaction committed by context manager
4
5with engine.connect() as connection:
6 result = connection.execute(text("select * from artists where artistid=99999"))
7 print(result.first())
8
9with engine.begin() as connection:
10 result = connection.execute(text("delete from artists where artistid=99999"))
(99999, 'Fintech')
You can also put the connection into “auto commit” mode, in which each statement forms a transaction itself and is automatically committed.
1with engine.connect() as connection:
2 connection = connection.execution_options(isolation_level="AUTOCOMMIT")
3 result = connection.execute(text("insert into artists (artistid,name) values(99999,'Fintech')"))
4
5with engine.connect() as connection:
6 result = connection.execute(text("select * from artists where artistid=99999"))
7 print(result.first()) # Transaction auto-committed through execution options
8
9with engine.begin() as connection:
10 result = connection.execute(text("delete from artists where artistid=99999"))
11 # committed implicitly with begin() and context manager
(99999, 'Fintech')
To cancel a transaction explicitly, use rollback()
Parameterized Query#
A parameterized query (prepared statement) contains placeholders for parameters whose values are specified when the query executes.
These queries have a number of advantages:
To avoid SQL injection attacks.
To avoid needing to encode special characters in field values.
Performance
As these queries are created on the target database system, that system compiles the query. This both prevents the structure of the the query from being altered through an injection attack as well as speeds performance as the query plan is pre-determined.
SQL Alchemy utilizes a :variableName scheme for parameters.
1with engine.connect() as connection:
2 query = text("select artistID, name from artists where artistid = :id")
3 result = connection.execute(query,{"id": 1})
4 print(result.first())
(1, 'AC/DC')
With insert and update queries, we can also send multiple records to be executed. Behind the scenes, the SQL statement is executed once for each parameter set. This is also known as “executemany”.
1with engine.connect() as connection:
2 query = text("insert into artists (artistid,name) values(:id, :name)")
3 values = [ { "id" : 99999, "name" :"Fintech" }, {"id" : 99998, "name" : "RockStart"}]
4 result = connection.execute(query,values)
5 print(result.rowcount,"record(s) inserted")
6 connection.commit() # mark the change as successful. Database will commit the change
7
8 query = text("select artistID, name from artists where artistid > :id")
9 result = connection.execute(query,{"id": 99990})
10 print(result.all())
11
12 # Now, remove those added records
13 query = text("delete from artists where artistid > :id")
14 result = connection.execute(query,{"id": 99990})
15 print (result.rowcount, "record(s) removed")
16 connection.commit()
2 record(s) inserted
[(99998, 'RockStart'), (99999, 'Fintech')]
2 record(s) removed
1with engine.connect() as connection:
2 query = text("delete from artists where artistid > :id")
3 result = connection.execute(query,{"id": 99990})
4 print(result.rowcount)
5 connection.commit()
0
Converting SQL Alchemy Results to a Pandas DataFrame#
1import pandas as pd
2with engine.connect() as connection:
3 query = text("select c.country, i.invoicedate,i.total from customers c, invoices i where c.customerid=i.customerid")
4 result = connection.execute(query)
5 df = pd.DataFrame(result.all())
6 df.columns = result.keys()
7 print(df)
Country InvoiceDate Total
0 Brazil 2010-03-11 00:00:00 3.98
1 Brazil 2010-06-13 00:00:00 3.96
2 Brazil 2010-09-15 00:00:00 5.94
3 Brazil 2011-05-06 00:00:00 0.99
4 Brazil 2012-10-27 00:00:00 1.98
.. ... ... ...
407 India 2009-07-08 00:00:00 5.94
408 India 2010-02-26 00:00:00 1.99
409 India 2011-08-20 00:00:00 1.98
410 India 2011-09-30 00:00:00 13.86
411 India 2012-05-30 00:00:00 8.91
[412 rows x 3 columns]