10

We are implementing a database in a student record project. We want to see that how many rows are there in a table before and after deleting a row from a table. The code we tried is as follows:

1  roll=5
2  m = mysql.connector.connect(host='localhost', database='student',user='root', password='')
3  cur = m.cursor()
4  rc = cur.rowcount
5  print("%d"%rc)
6  e=cur.execute("DELETE FROM `acc_details` WHERE roll_No=%s" % roll)
7  print("%d"%cur.rowcount) 

In the above code, the first rowcount in line 4 is giving -1 as the output and the rowcount in the last line is giving the no of rows that the table has after deleting a row.

Why is the first rowcount in line 4 give -1 as the output?

Any help shall be great.

nishant
  • 103
  • 1
  • 1
  • 6

3 Answers3

16

As per the document of psycopg2, cur.rowcount returns the number of rows affected by the last execute method for the same cur object and thus it returns -1 for the first cur.rowcount call as there is no previous execute() method.

You can try this-

roll=5 
m = mysql.connector.connect(host='localhost', database='student',user='root', password='')
cur = m.cursor()
cur.execute("SELECT * FROM `acc_details`")
cur.fetchall()
rc = cur.rowcount
print("%d"%rc)
e=cur.execute("DELETE FROM `acc_details` WHERE roll_No=%s" % roll)
print("%d"%cur.rowcount) 
Pankhuri Agarwal
  • 764
  • 3
  • 23
  • thank you for the response but this gives a error message: mysql.connector.errors.InternalError: Unread result found – nishant Jul 07 '17 at 05:34
  • Dint noticed that you were using mysql. Please check the edit at line number 4 of code in answer. Should work now. – Pankhuri Agarwal Jul 07 '17 at 05:42
3

have your code include

m.commit()
cur.close()
m.close()

If your code don't have these, maybe you can add them. and your first 4 lines ,I think you should add

cur.execute('select * from 'table_name'')
cur.fetchall()

then you can get the rowcount.I hope my answer can help you.

cwl
  • 184
  • 1
  • 1
  • 10
1

cursor.rowcount will output -1 until you have fetched all rows of the result. Unless you are using a buffered cursor, you should use cursor.fetchall() before getting the real number of rows.

oss
  • 115
  • 8
Caresth
  • 21
  • 4
  • Great clarification that cursor.fetchall() is required after a SELECT statement. But cursor.rowcount is not a function, it's just a **property** https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-rowcount.html – Bob Stein Feb 07 '20 at 00:54