不获取而获取MySQL游标行数

时间:2018-12-04 09:10:32

标签: python mysql python-3.x mysql-connector-python

我正在使用Python MySQL Connector,我想知道我的select语句返回了多少行而不必先获取它们。我正在使用的示例代码:

import mysql.connector

config = {
    'user': 'sample_user',
    'password': 'sample_password',
    'host': '127.0.0.1',
    'database': 'sample_database'
    }

connection = mysql.connector.connect(**self.config)

cursor = connection.cursor()

query = """
        SELECT *
        FROM sample_table
        """

cursor.execute(query)

count = cursor.rowcount 
print(count) # This prints -1 as the rows have not yet been fetched

i = 0
for row in cursor:
    i += 1
    # Save row to file
    print("Progress {:2.1%}".format(i / count), end="\r") # This prints a negative number since count is -1

我想显示获取进度,但是为此,我需要在获取之前使用SELECT语句选择的总行数。

有没有一种方法可以在不先获取或运行单独的SELECT COUNT(*)查询的情况下检索行计数?

1 个答案:

答案 0 :(得分:0)

否,除非您另外存储了行计数值。

实际上,两个游标对象都不会提供流结果,您应该使用limit / offset关键字逐批迭代整个表。