PostgreSQL Wrapper Using Python And PyGreSQL

Ever wanted a nice, clean or sexy interface when working with Python and PostgreSQL? You're in luck, I happen to own one. I wrote this a year or so ago and it's been through some changes but overall it works very well. It is in use over at AhCabron (NSFW) and has been performing great for the site, which pulls 8M+ page views per month (I know, that's not a HUGE amount of traffic, but it's respectable).

Of course, for web work with Python I strongly recommend Django! But there are still plenty of other reasons why you need to hit a db outside of Django. That's where my module comes in.

It uses the PyGreSQL PostgresSQL module. This is the actual glue for Python to PostgreSQL. My module is what makes your programming super simple. So here it is, I am releasing it to the wild and under the BSD License. Do with it what you will.. Download it here

Here is an example of how to use it.. Very simple.


from sql import *

try:
sql = PgSQL('dbuser', 'dbpass', 'dbhost', 'dbport')
sql.Connect('dbname')

query = 'SELECT * FROM table WHERE "foo"=\'?\' and "bar"=\'?\''
sql.Prepare(query, (var1, var2)) # Prepare takes 2 items only. a query and a tuple (or single object)
sql.Execute()

for x in xrange(sql.rows):
print sql.data[x][0] # Column count here

sql.Close()
except SQLError, err:
print 'Caught err: %s' % (err)

Pretty self explanatory. If you have questions, check out the source. It's not a large module and pretty easy to follow. If you still have issues, feel free to email me. Upon any error, the exception it will raise is SQLError. I thought about adding more specific exceptions, but in the end, is it really necessary?

So there you go. Enjoy!