formating query with empty parameter
python.list at tim.thechases.com
Mon May 25 18:16:48 CEST 2009
>> To stave off this problem, I often use:
>> values = [
>> params = ', '.join('%s' for _ in values)
>> query = """
>> INSERT INTO table
>> VALUES (%s);
>> """ % params
>> self.db.execute(query, values)
> Why do you pass values to execute() if you already have your query
The "params" might be better named "placeholders". So after the
query = "..." % params
the query looks like your original (go ahead and print "query" to
see), only the number of placeholders ("%s") is guaranteed to
match the number of values you pass in during the execute() call.
The second iteration I gave goes one step further to ensure
that the "(a,b,c,d,e,f,g)" portion also matches in count to the
number of values and place-holders to be used.
Once you have a SQL query that matches what you plan to pass
(based on your initial data-structure: a list/tuple or a
dictionary), then you call execute(query, values) to have the
database then associate the parameter-placeholders ("%s") with
the corresponding value from "values".
More information about the Python-list