Reputation: 498
In pyodbc
, cursor.rowcount
works perfectly when using cursor.execute()
. However, it always returns -1
when using cursor.executemany()
.
How does one get the correct row count for cursor.executemany()
?
This applies to multiple inserts, updates, and deletes.
Upvotes: 7
Views: 10717
Reputation: 36
I believe that you can do first another database query, avoiding this problem of Pyodbc, having the line count then.
Create another cursor before the actual desired query cursor, "cursor0" for example. Then you make a SELECT COUNT(*) FROM desiredTable WHERE desiredConditions.
I think it is easier if you can see a bit of the code.
cursor = cnxn.cursor()
cursor2 = cnxn.cursor()
cursor.execute("SELECT COUNT(*) FROM myTable")
row = cursor.fetchone()
print (str(row[0]))
cursor2.execute("SELECT * FROM myTable")
row = cursor2.fetchone()
while row:
print(str(row))
I hope that I've helped in someway.
I've tested the code before answering, I believe it works on the code you was working on or for learning purposes.
Upvotes: 1
Reputation: 2862
You can't, only the last query row count is returned from executemany, at least that's how it says in the pyodbc code docs. -1 usually indicates problems with query though. If you absolutely need the rowcount, you need to either cursor.execute in a loop or write a patch for pyodbc library.
Upvotes: 1