dynamic if statement

Tim Chase python.list at tim.thechases.com
Tue Jun 18 10:56:17 EDT 2013


On 2013-06-18 07:10, upperdecksu at gmail.com wrote:
> I have a set of queries that are run against various
> databases/tables.  The result is all the same in that I always get
> back the same field names.
> 
> I query fld1, fld2, fld3, qty, qty2 from table1
> then I loop thru the results 
>   if fld1 = 'a' add qty to some_total1 
...
> I created a database pair that contains (table1,fld1 = 'a',add qty
> to some_total1) (table2,fld2 = 'b',qty to some_total1)
>                                     (table3,fld3 = 'c',qty2 to
> some_total1)

Given the data-structure you have, and that it's hard-coded (rather
than able to take dynamic/dangerous user input) for the table-name,
I'd do something like this (untested)

  for tablename, compare_field, compare_value, source_field in (
      ("table1", "fld1", "a", "qty"),
      ("table2", "fld2", "b", "qty"),
      ("table3", "fld3", "c", "qty2"),
      ):
    # using string-building rather than escaping because
    # 1) we know the tablenames are hard-coded/safe from above, and
    # 2) this sort of escaping often chokes query parsers
    query = "SELECT fld1, fld2, fld3, qty, qty2 from %s" % tablename
    cursor.execute(query)

    name_index_map = dict(
      (info[0], i)
      for info, i in enumerate(cursor.description)
      )
    for row in cursor.fetchall():
      db_value = row[name_index_map[compare_field]]
      if db_value == compare_value:
        addend = row[name_index_map[source_field]]
        some_total_1 += addend

-tkc








More information about the Python-list mailing list