better way?

someone petshmidt at googlemail.com
Tue Aug 11 18:33:52 CEST 2009


Hello,

I'd like to make insert into db if record not exist otherwise update.
to save typing list of columns in both statements I do following

query = "SELECT location FROM table WHERE location = %s AND id = %s;"
result = self._getResult(db, query, [location,id])

fields = ['id', 'location', 'wl', 'modified', 'counter', 'name']
if result:
    t = map(lambda s: s + ' = %s', fields)
    temp = ", ".join(t)
    query = "UPDATE table SET " + temp + " WHERE location = %s AND id
= %s;"
    self._execQuery(db, query, [id, location, self.wl, 'NOW()', 1,
name, location, id])
else:
    f = ", ".join(fields)
    query = """
        INSERT INTO table
        (""" + f + """)
        VALUES
        (%s,%s,%s,NOW()- interval '1 day', 1, %s)
    """
    self._execQuery(db, query, [id, location, self.wl, name])



is there better or more readable way to do it?

Pet



More information about the Python-list mailing list