[GIS] Create Table with postGIS geometry in Python

postgispsycopg2python

I'm creating the following table with a postGIS geometry column in python but get an error psycopg2.ProgrammingError: type "geometry" does not exist
What should I use to be able to use postGIS in python?

import psycopg2

def main():
        conn_string = "host='localhost' dbname='postgres' user='postgres' password='postgres'"
        conn = psycopg2.connect(conn_string)
        conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)
        cursor = conn.cursor()


        createTable = """  CREATE TABLE map
                        (
                            id INT PRIMARY KEY DEFAULT NULL,
                            geom GEOMETRY DEFAULT NULL,
                        );
                        """
        cursor.execute(createTable)
        conn.commit()
        cursor.close()
        conn.close()
if __name__ == "__main__":
    main()

Best Answer

to do so you only need to add the postgis extension.

cursor.execute("CREATE EXTENSION postgis;")

and then create the table

createTable = """  CREATE TABLE map
                        (
                            id INT PRIMARY KEY DEFAULT NULL,
                            geom GEOMETRY DEFAULT NULL,
                        );
                        """
        cursor.execute(createTable)
Related Question