Python 行数返回负数 1

Python rowcount returning negative 1

请有人帮忙,我不敢相信我没有做对。我正在尝试计算 mysql 数据库中的行数。正确的数字是 7,但是每次我执行以下命令时,我都会得到 -1 的答案。使用 python 3.4.4

建立连接 successfully.I
import mysql.connector

config = {
'user': 'root', 
'password': '', 
'host': '127.0.0.1',
'database': 'test'
}  
cnx =mysql.connector.MySQLConnection(**config)

if cnx.is_connected():
   print('Connected to MySQL database')

cursor = cnx.cursor()
cursor.execute("SELECT * FROM test")
numrows = int (cursor.rowcount)
print(numrows)

根据 documentation:

For nonbuffered cursors, the row count cannot be known before the rows have been fetched. In this case, the number of rows is -1 immediately after query execution and is incremented as rows are fetched.

这意味着,为了 .rowcount 在这种情况下工作,您必须先 获取结果

cursor.execute("SELECT * FROM test")
rows = cursor.fetchall()
numrows = int(cursor.rowcount)

当然也可以获取rows列表的长度