How to find bad row with db api executemany()?

Roy Smith roy at
Sat Mar 30 17:44:55 CET 2013

In article <6b085f98-0d19-4572-be92-4fb1764a221b at>,
 Miki Tebeka <miki.tebeka at> wrote:

> > I can catch the exception, but don't see any way to tell which row caused 
> > the problem.  Is this information obtainable, short of retrying each row 
> > one by one?
> One way to debug this is to wrap the iterable passed to executemany with one 
> that remembers the last line. Something like:
>     class LastIterator(object):
>         def __init__(self, coll):
>    = iter(coll)
>             self.last = None
>         def __iter__(self):
>             return self
>         def next(self):
>             self.last = next(
>             return self.last
>       ...
>       li = ListIterator(items)
>       try:
>            cursor.executemany(sql, li)
>       except SQLError, e:
>            print('Error: {}, row was {}'.format(e, li.last))

This assumes that the exception is raised synchronously with iterating 
over the input.  The whole idea of executemany() is to batch up rows and 
send them to the database as a single unit, so this would almost 
certainly not be a good assumption.

More information about the Python-list mailing list