Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python cx_oracle cursor.rowcount returning 0 but cursor.fetchall returns data

I have this code where I am executing a select sql statement from python code using cx_oracle package:

import cx_Oracle

try:
    cur = conn.cursor()
    result = cur.execute('select * from table1')
    print(str(cur.rowcount))
    print(cur.fetchall())

except Exception as e:
    print(e)

When I execute the above code I see 0 coming in for cur.rowcount but I see following data getting printed for cur.fetchall():

[('185',), ('1860',), ('1908',)]

cx_Oracle package documentation does mention Cursor.rowcount as a valid operation so I am not sure why in my code it is returning 0 even though the data is coming?

like image 601
user2966197 Avatar asked Aug 31 '17 16:08

user2966197


People also ask

What is cursor in cx_Oracle?

Cursor. parse(statement) This can be used to parse a statement without actually executing it (this step is done automatically by Oracle when a statement is executed). The DB API definition does not define this method. You can parse any DML or DDL statement.

What is cursor Arraysize?

Cursor. arraysize. This read-write attribute specifies the number of rows to fetch at a time internally and is the default number of rows to fetch with the fetchmany() call. It defaults to 100 meaning to fetch 100 rows at a time.

How do you use Fetchmany?

fetchmany() Method. This method fetches the next set of rows of a query result and returns a list of tuples. If no more rows are available, it returns an empty list. The number of rows returned can be specified using the size argument, which defaults to one.


2 Answers

cx-oracle.readthedocs mentioned Cursor.rowcount specified number of rows affected by insert, update and delete statement. You are using a select statement.

cur.execute('select * from table1')
result = cur.fetchall()
print (len(result)) # this will return number of records affected by select statement
print (result)
like image 116
S.Yang Avatar answered Oct 24 '22 04:10

S.Yang


The documentation states that cursor.rowcount specifies the number of rows that have currently been fetched. Immediately after the cursor.execute() call has been made, no rows have been fetched, so the result is 0. If you call cursor.fetchone() then result will be 1 and if you call cursor.fetchmany(5), then the result will be 6, and so forth (assuming there are enough rows to satisfy your requests, of course!).

like image 8
Anthony Tuininga Avatar answered Oct 24 '22 04:10

Anthony Tuininga