The Artima Developer Community
Sponsored Link

Python Buzz Forum
SQLObject

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Simon Willison

Posts: 282
Nickname: simonw
Registered: Jun, 2003

Simon Willison is a web technology enthusiast studying for a Computer Science degree at Bath Uni, UK
SQLObject Posted: Sep 1, 2003 6:43 PM
Reply to this message Reply

This post originated from an RSS feed registered with Python Buzz by Simon Willison.
Original Post: SQLObject
Feed Title: Simon Willison: Python
Feed URL: http://simon.incutio.com/syndicate/python/rss1.0
Feed Description: Simon Willison's Python cateory
Latest Python Buzz Posts
Latest Python Buzz Posts by Simon Willison
Latest Posts From Simon Willison: Python

Advertisement

My new favourite toy is SQLObject, an object-relational mapper which makes heavy use of Python's special method names to create objects which can be used to transparently access and modify data in a relational database. I tried to write something like this in PHP once before and failed miserably, but SQLObject has such an elegant design that I'm just annoyed I didn't find out about it sooner. Here's some example code, adapted from the SQLOBject site:

from SQLObject import *
# Set up a database connection
__connection__ = PyPgSQLConnection()

# This class defines a table
class Person(SQLObject):
    firstName = StringCol(length=100)
    middleInitial = StringCol(length=1, default=None)
    lastName = StringCol(length=100)

# Now create the table (if running for the first time)
Person.createTable()

# Create a record for me
p = Person.new(firstName='Simon', lastName='Willison')

print p
# Outputs <Person 1 firstName='Simon' middleInitial=None lastName='Willison'>

# Set my middle initial (updates the database)
p.middleInitial = 'P'

# Print my full name
print p.firstName, p.middleInitial, p.lastName

SQLObject has plenty more tricks up its sleeve: it can create class definitions by introspecting a database table, handle one to many and many to many joins, and generate complicated SELECT statements on the fly using simple, database independant syntax. It comes with support for MySQL, Postgres and SQLite. Postgres support uses the psycopg module, but we use pyPgSQL so I wrote a simple connection wrapper to support that module which I've submitted to the SQLObject mailing list.

Read: SQLObject

Topic: Templating (Also: ARGH) Previous Topic   Next Topic Topic: Handling Mailboxes in Python

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use