This article describes how to connect to a PostgreSQL database using Python.
Before you can access PostgreSQL databases using Python, you must install one (or more) of the following packages in a virtual environment:
Both of these packages support Python's portable SQL database API. This means that if you switch from one module to another, you can reuse almost all of your existing code (the code sample below demonstrates how to do this).
To set up the Python virtual environment and install a PostgreSQL package, follow these steps:
cd ~ virtualenv -p /usr/bin/python2.7 sqlenv
To activate the virtual environment, type the following command:
Type the command for the package you want to install:
pip install psycopg2
To install the PyGreSQL package, type the following command:
pip install pygresql
After you install a PostgreSQL package in the virtual environment, you are ready to work with actual databases. The following sample Python code demonstrates how to do this, as well as just how easy it is to switch between the different SQL package implementations using the portable SQL database API.
In your own code, replace USERNAME with the PostgreSQL database username, PASSWORD with the database user's password, and DBNAME with the database name:
#!/usr/bin/python hostname = 'localhost' username = 'USERNAME' password = 'PASSWORD' database = 'DBNAME' # Simple routine to run a query on a database and print the results: def doQuery( conn ) : cur = conn.cursor() cur.execute( "SELECT fname, lname FROM employee" ) for firstname, lastname in cur.fetchall() : print firstname, lastname print "Using psycopg2…" import psycopg2 myConnection = psycopg2.connect( host=hostname, user=username, password=password, dbname=database ) doQuery( myConnection ) myConnection.close() print "Using PyGreSQL…" import pgdb myConnection = pgdb.connect( host=hostname, user=username, password=password, database=database ) doQuery( myConnection ) myConnection.close()
This example creates a series of Connection objects that opens the same database using different PostgreSQL modules. Because both of these modules use the portable SQL database API interface, they are able to use the code in the doQuery() function without any modifications.
When you have a Connection object associated with a database, you can create a Cursor object. The Cursor object enables you to run the execute() method, which in turn enables you to run raw SQL statements (in this case, a SELECT query on a table named employee).
The PyGreSQL package also includes a legacy pg module that you can use to connect to PostgreSQL. Although it is easy to use, it does not implement Python's portable SQL database API.
The following code sample demonstrates how to use the pg module to connect to a PostgreSQL database. Replace USERNAME with the PostgreSQL database username, PASSWORD with the database user's password, and DBNAME with the database name:
#!/usr/bin/python import pg conn = pg.DB(host="localhost", user="USERNAME", passwd="PASSWORD", dbname="DBNAME") result = conn.query("SELECT fname, lname FROM employee") for firstname, lastname in result.getresult() : print firstname, lastname conn.close()
This example creates a Connection object that opens the PostgreSQL database using the specified parameters. Once you have a Connection object associated with the database, you can query the database directly using raw SQL statements (in this case, a SELECT query on a table named employee). The getresult() method reads the result data returned by the query. Finally, the close() method closes the connection to the database.