Let's write another Python program to perform various queries against the contents of our database. Start by creating another Python file named query_data.py
and place it into the world_borders
directory. We start by importing the psycopg2
library, opening up a connection to our database, and creating a database cursor:
import psycopg2 connection = psycopg2.connect(database="world_borders", user="...", password="...") cursor = connection.cursor()
This should all be familiar from the create_table.py
program we created earlier.
Let's now perform a simple (non-spatial) database query, just to see how it works. Add the following to the end of your program:
cursor.execute("SELECT id,name FROM borders ORDER BY name") for row in cursor: print row
When you run your query_data.py
program, you should see a list of the record IDs and associated names, taken from your borders
table:
(1264, 'Afghanistan') (1237, 'Albania') (1235, 'Algeria') ...
Notice that you use cursor.execute...