12: conn.close()
When you write the for loop, you must specify a variable for each data field that you return in the
SELECT statement. For each iteration, the data fields contain the values for one data record in the
query results. When the loop completes, you should have iterated through all the individual data
records. When you run the script, you should get a listing of all the data records you stored in the
employees table:
Click here to view code image
pi@raspberrypi ~ $ python3 script2102.py
1 Blum Barbara 45000.0
2 Blum Rich 30000.0
pi@raspberrypi ~ $
Congratulations! You’ve just written a database program using Python. Now let’s take a look at how
to do the same thing with the other popular Linux database server, PostgreSQL.
Using the PostgreSQL Database
The PostgreSQL database started out as an academic project to demonstrate how to incorporate
advanced database techniques into a functional database server. Over the years, PostgreSQL has
evolved into one of the most advanced open-source database servers available for the Linux
environment.
The following sections walk you through getting a PostgreSQL database server installed and running
on your Raspberry Pi and then setting up your Python scripts to interact with the PostgreSQL database
to store and retrieve data.
Installing PostgreSQL
For the PostgreSQL server installation on the Raspberry Pi, both the PostgreSQL server and client
programs are contained in a single software package. You just install the postgresql package by
using the apt-get utility, as shown here:
Click here to view code image
pi@raspberrypi ~ $ sudo apt-get install postresql
After you do this, you have a fully functional PostgreSQL server up and running. The installation
process automatically starts the PostgreSQL server, so there’s nothing for you to manually run. Next,
you need to create the database objects for your Python scripts.
Setting Up the PostgreSQL Environment
Just as with the MySQL environment, you need to create your database objects in the PostgreSQL
environment before you start your Python scripting.
For the Python environment, the command-line program you use to interact with the PostgreSQL
server is called psql. However, it works a little differently from the mysql command-line program
in MySQL.
PostgreSQL uses the Linux system user accounts instead of maintaining its own database of user
accounts. While this can sometimes be confusing, it does make for a nice, clean way to control user
accounts in PostgreSQL. All you need to do is ensure that each PostgreSQL user has a valid account