formating query with empty parameter

Pet petshmidt at googlemail.com
Mon May 25 16:53:06 CEST 2009


On May 25, 2:50 pm, Peter Otten <__pete... at web.de> wrote:
> Pet wrote:
> > > someone wrote:
> > > > Hello!
>
> > > > if one of parameter in values is empty, I'm getting
> > > > TypeError: not enough arguments for format string
>
> > > > But how to handle such situation? It is ok for DB, that some of values
> > > > are empty.
>
> > > > def __insert(self, data):
> > > >         query = """
> > > >             BEGIN;
> > > >                 INSERT INTO table
> > > >                     (a,  b,  c,  d,  e,  f,  g)
> > > >                     VALUES
> > > >                     (%s, %s, %s, %s, %s, %s, %s);
> > > >             COMMIT;
> > > >             """
> > > >         values = [
> > > >             data['a'],
> > > >             data['b'],
> > > >             data['c'],
> > > >             data['d'],
> > > >             data['e'],
> > > >             data['f'],
> > > >             data['g']
> > > >             ]
> > > >         self.db.execute(query, *values)
>
> > > You need to pass
>
> > > None
>
> > Hi,
>
> > thanks for reply.
> > Unfortunately, it doesn't work. Still getting TypeError: not enough
> > arguments for format string
>
> The code you posted doesn't match that error message. You have to invoke
> cursor.execute() as
>
> cursor.execute(query, values) # correct
>
> , not
>
> cursor.execute(query, *values) # wrong

as far as I know it is not wrong, at least for pyPgSQL it takes values
and escapes properly preventing sql injections

>
> or
>
> cursor.execute(query % values) # wrong
>
> The length of values must match the number of "%s" occurences in the sql
> query, but as Diez indicated you may pass None for every field that allows a
> NULL value in the table.
>
> Peter




More information about the Python-list mailing list