1. Computing & Technology

Reading from a PostgreSQL Database With Python

From , former About.com Guide

Forming the PostgreSQL SELECT Statement

Now we can define the statement we would have executed. Since the variables are already defined at runtime (i.e., when the program is executed), we can create the statement and plug the variables in like concatenating a string.

 statement = 'SELECT * FROM ' + table + ' WHERE ' + column + ' ' + operator + ' ' + string 
Do note that this statement will work for any value. When using this statement one must supply the quotes for any character strings. However, if one wants to match character strings alone, not allowing for numerical calculations, one may supply the quotes within the statement itself.
 statement = 'SELECT * FROM ' + table + ' WHERE ' + column + ' ' + operator + ' \'' + string +\ '\'' 
If you use this statement instead of the previous one, it is a good idea to evaluate the variable operator and to reject any numerical operators. Otherwise, PostgreSQL, and therefore both psycopg and Python, will throw an error.

©2012 About.com. All rights reserved.

A part of The New York Times Company.