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 queries. You can then retrieve the matching data, as shown in this example.
Let's use psycopg2
to store the World Borders Dataset into a spatial database table and then perform some simple queries against that...