我正在使用 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(*)
查询的情况下检索行计数?
最佳答案
否,除非您已存储行计数值。
实际上,游标对象都不会给出流式结果,您应该通过 limit/offset 关键字批量迭代整个表。
关于python - 无需提取即可获取 MySQL 游标行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53609266/