Use Db2 as Cloud SQL Database with Python

5 min read

By: Henrik Loeser

Use Db2 as Cloud SQL Database with Python

Over the Summer I learned that Python is top in the IEEE programming languages ranking. It is also my favorite language for quickly coding tools, web apps and analyzing data with notebooks (e.g., on IBM Data Science Experience). Did you know that IBM provides four (4) different Db2 drivers for Python? There is a driver with the native Db2 API, one that supports the official Python DBI (database interface), one for the popular SQLAlchemy Python SQL Toolkit, and for the Python-based Django Web Framework. In an older blog I showed you how to use SQLAlchemy with Db2. Today, I am going to demonstrate you how simple it is to create a SQL database-backed web app in the IBM Cloud, utilizing the native Db2 API.

Overview

The app is based on the Flask web framework and provides access to city information. The data comes from GeoNames.  After the data has been loaded into Db2, it is accessed by the app and displayed using a simple page template. Users can search via a form or directly access city information through static URIs.

I put the source code and all required instructions into a Github repository which you can find at https://github.com/data-henrik/cloud-sql-database. The included README takes you through all the steps from provisioning a Db2 database on the IBM Cloud, over creating a table and loading data to how to deploy the app. Make sure to take a look at the (few 🙂 comments in the files that provide additional insight. Here are some takeaways:

  • First, you can connect from outside the IBM Cloud to Db2 Warehouse on Cloud. Thus, you could use an SQL Editor on your machine to interact with the database.

  • Adding to that, the database console has a download section for drivers, database tools, and more.

  • Noteworthy, Db2 Warehouse on Cloud supports several ways of uploading data to be loaded into tables. You could even send in storage devices to an IBM data center (“truckload of data”?).

  • Use parameter markers and prepare SQL statements to improve app security. It reduces the risk of attacks via SQL injection.

  • Last but not least, you can automatically bind a database service to an app using a manifest file.

I hope you are going to enjoy it. If you have feedback, suggestions, or questions about this post, please reach out to me on Twitter (@data_henrik) or LinkedIn.

Be the first to hear about news, product updates, and innovation from IBM Cloud