Connecting to PostgreSQL databases from Python provides the ability to run essential SQL queries that can be utilized in geoprocessing tasks.
Instructions provided describe how to connect to a PostgreSQL database and run SQL queries from a Python script.
- Download and install the appropriate psycopg2 module for the installed Python release (for example, Python 2.6, 2.7, etc.):
- Import the module in the Python script:
- Make a connection to a PostgreSQL database by passing in the appropriate user/password to the following connection string:
connection = psycopg2.connect(host='prod', database='sde', user='sde', password='sde')
- Define a parameter to access the cursor method:
cursor = connection.cursor()
- Create a query string and pass to cursor method:
cursor.execute('select * from PARCELS WHERE OBJECTID < 70000')
- Create a for loop and print results
for query in cursor: