close
The Wayback Machine - https://web.archive.org/web/20090201100128/http://python.about.com:80/od/pythonanddatabases/ss/postgresqlread_7.htm

Python

  1. Home
  2. Computing & Technology
  3. Python

Reading from a PostgreSQL Database With Python

By Al Lukaszewski, About.com

7 of 9

Executing the SELECT Statement Through Psycopg

Next, we need to tell psycopg to pass the statement to PostgreSQL. We do this by use the method 'execute', a method of connection.cursor(). The next statement thus looks like this:

     mark.execute(statement)
The data returned will be an array of lists, one list for every line returned.

Given how flexible Python tends to be, one might ask why we define statement separately instead of passing its contents directly to execute. By defining statement separately, one is able to debug the program with fewer complications by simply inserting a print command at the appropriate point.

Consider, for example: PostgreSQL keeps throwing an error (e.g., "ERROR: syntax error at or near "' "]). You look at the SELECT statement a thousand times and still cannot figure out what is off. If you have embedded the statement, you have no way of printing the argument and thereby seeing the SELECT statement from the computer's perspective. If you define it separately, you can print it and better grasp where things are awry. In this way, form is kept separate from function.

7 of 9

Explore Python

More from About.com

Python

  1. Home
  2. Computing & Technology
  3. Python
  4. Database Programming
  5. Reading PostgreSQL With Python - Executing the SELECT Statement Through Psycopg

©2009 About.com, a part of The New York Times Company.

All rights reserved.