is it possible to fetch all the lastrowids after executemany insert in mysqldb?
Asked Answered
S

1

16

I cannot be sure whether the ids generated is continously,if not,is there any otherway to get them?

class BaseDao(object):

    def __init__(self,pooldb):
        self.pooldb = pooldb

    def insertmany(self,sql,args):
        conn,cur = None,None
        try:
            conn = pooldb.dedicated_connection()
            cur = conn.cursor()
            num=cur.executemany(sql,args)
            if num <= 0:
                raise Exception("insert failure with num equals zero")
            lastrowid = int(cur.lastrowid)
            return [range(lastrowid - num + 1,lastrowid+1)]
        except:
            conn.rollback()
            traceback.print_exc()
            raise Exception("error happened when insert sql=%s args=%s " % (sql,str(args)))
        finally:
            if cur:
                cur.close()
            if conn:
                conn.close() 
Semester answered 22/3, 2012 at 5:52 Comment(0)
I
13

Every time mysqldb executes a query involving an auto-increment column, the last insert ID will be lost unless you read it before the next execute(), which with an executemany() you won't be able to do.

You would have to change the above code to something like:

num = 0
insert_ids = []

for arg in args:
    num += cur.execute(sql, arg)
    insert_ids.append(cur.lastrowid)

Since the Python module is really a thin layer over the MySQL API, here is some insight into how the mysql_insert_id() function works.

Indrawn answered 26/3, 2012 at 22:17 Comment(1)
well,I wont give any hope do gradefully resolve it except execute sequencially,just like what u saidSemester

© 2022 - 2024 — McMap. All rights reserved.