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

Get Python Geospatial Development - Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.