python - MySQLdb.cursors.Cursor.execute 在不同游标的情况下返回不同的值,为什么?

标签 python cursor mysql-python

看这两个Python代码片段,

conn = MySQLdb.connect(c['host'], c['user'], c['password'], c['db'])
cur = conn.cursor()
cur.execute("select * from geo_weathers;)   ->  **1147L**

conn = MySQLdb.connect(c['host'], c['user'], c['password'], c['db'], cursorclass=MySQLdb.cursors.SSCursor)
cur = conn.cursor()
cur.execute("select * from geo_weathers")   ->  **18446744073709551615L**

为什么上面两种情况返回的行数不同? 仅供引用,表中有 1147 行。

SSCursor 用于在服务器端保存结果。是这个原因吗? 此选择查询影响哪些所有行?

有人知道吗?

最佳答案

MySQLdb 使用的标准游标是存储结果游标。这意味着整个结果集会作为 execute() 调用的结果从服务器传输并缓存在客户端内存中。

SSCursor 是服务器端游标,只会根据请求将结果返回给客户端。

游标execute()调用将返回MySql C API函数的结果mysql_affected_rows()依次返回 mysql_num_rows() 的结果用于 SELECT 查询。

由于结果存储在服务器端,因此客户端在迭代结果之前不知道有多少行受到影响。

mysql_num_rows() 的文档是这样说的:

The use of mysql_num_rows() depends on whether you use mysql_store_result() or mysql_use_result() to return the result set. If you use mysql_store_result(), mysql_num_rows() may be called immediately. If you use mysql_use_result(), mysql_num_rows() does not return the correct value until all the rows in the result set have been retrieved.

如果您想获取行数,请使用 SELECT COUNT(*) from geo_weathers 而不是依赖于 execute() 调用的结果.

关于python - MySQLdb.cursors.Cursor.execute 在不同游标的情况下返回不同的值,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14551009/

相关文章:

postgresql - 在 pl/proxy 中获取 refcursor

css - 在 IE 11 的文本输入字段中更改光标

html - 更改光标(指针)图像

python - 检查 Python/MySQLdb 中的空查询集

python - 如果仅用于原始 sql,SQLAlchemy 性能如何?

python - DecisionTreeClassifier - 树的手动修剪

python - 扭曲 deferToThread 中的延迟中未处理的错误

python - 在 Linux 下模板文件更改时重新加载 Flask 应用程序

python - 3.x 之前的 Python 的正确 SQL 查询

Python TwitterAPI 问题... ImportError : cannot import name ReadTimeout