Polygons in the database

You can also store polygons using PostGIS. The following code will create a new table with a single polygon:

from shapely.geometry import Polygonconnection = psycopg2.connect(database="pythonspatial",user="postgres", password="postgres")cursor = conectionn.cursor()cursor.execute("CREATE TABLE poly (id SERIAL PRIMARY KEY, location GEOMETRY)")a=Polygon([(-106.936763,35.958191),(-106.944385,35.239293),           (-106.452396,35.281908),(-106.407844,35.948708)])cursor.execute("INSERT INTO poly (location)              VALUES (ST_GeomFromText('{}'))".format(a.wkt))connection.commit()

The previous code is almost identical to the Point and Line examples. Make the database connection and then get a cursor. Use execute() to create the table. Import ...

Get Mastering Geospatial Analysis with Python 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.