Newbie: Database technique

David M. Cook davecook at nowhere.net
Sat Dec 21 13:45:58 EST 2002


In article <mailman.1040436689.26831.python-list at python.org>, Joe 'shmengie'
Brown wrote:

> fields=("User_Role", "PRN_User", "Name", "Home_Phone", "Office_phone",
> "Mobile_phone", "Pager", "Fax_No", "Active_user","User_ID")
> oc.execute("SELECT " + ( ", ".join(fields)) + " FROM my_users")

That's basically what everyone does, but you might want to hide the details
of the string operation.  What I did was create a "Selector" class so that
the strings are pre-built for each query in the __init__ method.
Schematically:

class Selector:

    def __init__(self, ...):
    	# build self.qstr here


    def select(self, **keys):
        self.cursor.execute(self.qstr, keys)
        return self.cursor.fetchall()

Useful if you're building complex queries that will be executed many times.

I also have a Table class with update, insert, etc. methods.

Dave Cook



More information about the Python-list mailing list