getrowsaffectedcounts() Method

Returns the count of affected rows for the previous call to executemany(…, batcherrors=True). This method fails if executemany with batcherrors=True was not previously called on the cursor.

Syntax

cursor.getrowsaffectedcounts()

Returns

Tuple of rows affected counts for the previous call to executemany(…, batcherrors=True).

Example

The following example is based on the below table:
cursor = conn.cursor()
cursor.execute("create table testtable(a tinyint unique)")
cursor.close()
Case 1: Prepared execute of a statement with a batch of input parameter rows (BATCH/BULK INSERT/UPDATE/DELETE/SELECT):
cursor = conn.cursor()
try:
    cursor.executemany("insert into testtable(a) values(?)",[(1,), (2,)], batcherrors=True)
    rowsaffected = cursor.getrowsaffectedcounts()
    # check rowsaffected (should be = (1, 1))
    # Next line should result in a dbapi.ExecuteManyError being raised
    cursor.executemany("insert into testtable(a) values(?)", [(3,), (4,), (3,), (5,), (3,)], batcherrors=True)
except dbapi.ExecuteManyError as e:
    rowsaffected = cursor.getrowsaffectedcounts()
    # check rowsaffected (should be (1, 1, 0, 1, 0))
    for error_entry in e.errors:
        # process error by checking error_entry.errorcode, error_entry.errortext and error_entry.rownumber
cursor.close()
Case 2: Execute a list of direct statements:
cursor = conn.cursor()
try:
    cursor.executemany(["insert into testtable(a) values(20)",
                        "insert into testtable(a) values(30)"],
                        batcherrors=True)
    rowsaffected = cursor.getrowsaffectedcounts()
    # check rowsaffected (should be = (1, 1))
    # next line should result in a dbapi.ExecuteManyError being raised
    cursor.executemany(["insert into testtable(a) values(40)",
                        None], # Not a string
                        batcherrors=True) 
except dbapi.ExecuteManyError as e:
    rowsaffected = cursor.getrowsaffectedcounts()
    # Check rowsaffected
    for error_entry in e.errors:
        # process error by checking error_entry.errorcode, error_entry.errortext and error_entry.rownumber
cursor.close()
Case 3: Use getrowsaffectedcounts() outside of executemany(batcherrors=True):
cursor = conn.cursor()
try:
    # Next line should result in a dbapi.ProgrammingError
    rowsaffected = cursor.getrowsaffectedcounts()
except dbapi.Error as e:
    # process error
cursor.close()

cursor = conn.cursor()
try:
    cursor.execute("insert into testtable(a) values(60)")
    # Next line should result in a dbapi.ProgrammingError
    rowsaffected = cursor.getrowsaffectedcounts()
except dbapi.Error as e:
    # process error
cursor.close()

cursor = conn.cursor()
try:
    cursor.executemany("insert into testtable(a) values(?)",
                       [(150,), (200,)])
    # Next line should result in a dbapi.ProgrammingError
    rowsaffected = cursor.getrowsaffectedcounts()
except dbapi.Error as e:
    # process error
cursor.close()