O'Reilly logo

Python Geospatial Development - Third Edition 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

Using PostGIS

Now that we have a spatial database, let's see how to access it from Python. Using psycopg2 to access a spatial database from Python is quite straightforward. For example, the following code shows how to connect to the database and issue a simple query:

import psycopg2

connection = psycopg2.connect(database="...", user="...",
                              password="...")
cursor = connection.cursor()
cursor.execute("SELECT id,name FROM cities WHERE pop>100000")
for row in cursor:
    print(row[0],row[1])

The psycopg2.connect() statement opens up a connection to the database using the database name, user, and password you set up when you created and configured the database. Once you have a database connection, you then create a Cursor object against which you can execute ...

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