elegent sql building

Chris Perkins chris.perkins at inbusiness.com
Thu Dec 13 10:15:11 EST 2001


cmedcoff at home.com (Charles Medcoff) wrote in message news:<1a241b9d.0112121450.7aa92a12 at posting.google.com>...
> Damn.  I like that.
> 
> "Diving into Python" is the only published resource that goes into
> what I would consider "idoms" or advanced use.  I know that one has to
> put some time in the trenches (nothing like experience), but any
> resource along the lines of this that you can reference would be
> helpful.

Actually I have learned almost all of the (small amount) of Python
that I know by reading this newsgroup for several months. This is
probably one of the least efficient ways imaginable to learn a
language, but.. well, I wasn't in a hurry. After a few months stuff
started to sink in.
This method has one unfortunate effect: I seem to be catching on to
the tricky stuff, but I tend to not know some of the really basic
stuff that nobody asks questions about :(
Other than c.l.p, my best source of "idioms" has been reading:
1) The source of the library modules and the samples that ship with
Python
2) The Activestate Cookbook
3) And of course, as you said, "Dive Into Python" is excellent.

Chris Perkins

P.S.: here's a slightly more general version of my previous
suggestion:

def buildSql(tablename, **cols):
    return """
    SELECT *
    FROM   %s
    WHERE  1 = 1
    %s
    """ % (tablename, InList(cols))

class InList:
    def __init__(self, cols):
        self._cols = cols
    def __getitem__(self, colname):
        vals = self._cols[colname]
        if vals:
            return "AND %s IN ('%s')" % (colname, "','".join(vals))
        else:
            return ''
    def __str__(self):
        return '\n'.join([self[col] for col in self._cols.keys()])

then you can use any column names you need:

sql.buildSql(
        'foo',
        neep=['yak','nork','feep'], 
        yoop=['snurk','feep'], 
        grr=[])



More information about the Python-list mailing list