O'Reilly logo

Python Geospatial Analysis Essentials by Erik Westra

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Querying spatial data

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: ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required