formating query with empty parameter
Pet
petshmidt at googlemail.com
Mon May 25 13:17:44 EDT 2009
On 25 Mai, 18:16, Tim Chase <python.l... at tim.thechases.com> wrote:
> >> To stave off this problem, I often use:
>
> >> values = [
> >> data['a'],
> >> data['b'],
> >> data['c'],
> >> data['d'],
> >> data['e'],
> >> data['f'],
> >> data['g'],
> >> ]
> >> params = ', '.join('%s' for _ in values)
> >> query = """
> >> BEGIN;
> >> INSERT INTO table
> >> (a,b,c,d,e,f,g)
> >> VALUES (%s);
> >> COMMIT;
> >> """ % params
> >> self.db.execute(query, values)
>
> > Why do you pass values to execute() if you already have your query
> > formatted?
>
> The "params" might be better named "placeholders". So after the
O, thanks for clarification, I've completely missed the point of
params = ', '.join
>
> 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".
>
> -tkc
More information about the Python-list
mailing list