Skip to main content
 首页 » 编程设计

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

2024年08月29日24lexus

看看这两个 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() 调用的结果.