官方文档有cursor.rowcount ,但通常返回值是-1。
查询相关资料,得到答案如下:
没有可以直接得到行数的函数。sqlite事先不知道行数,遍历时才逐行返回。--->遍历完才知道的话,是否意味着并没有一次过将全部数据返回写入内存?
可以用 : result=cursor.fetchall() 然后 count=len(result) 获取。
或者执行一次 select count(*) from x where y 然后 fetchone 获取
From the SQLite3 FAQ here
Q) Which func could get the number of rows?
A) There is no function to retrieve the number of rows in a result set. SQLite doesn't know the number in advance, but returns row by row while iterating through the tables. The application can increment a row counter as needed at every successful sqlite3_step() .
Some wrappers are able to collect all rows in a resultset in a in-memory table, so they can return the number of rows.
You can always get the number of rows that a certain SELECT statement would return at the cost of some performance:
BEGIN IMMEDIATE TRANSACTION;
SELECT COUNT(*) FROM x WHERE y;
SELECT a,b,c FROM x WHERE y;
ROLLBACK TRANSACTION;
You have to wrap this in a transaction to prevent other connections from inserting / deleting rows between the two SELECT statements.
-------------
Although the Cursor
class of the sqlite3
module implements this attribute, the database engine’s own support for the determination of “rows affected”/”rows selected” is quirky. [官方文档]
在Python实现的DB API中,rowcount属性“当在特定类型数据库接口未实现cursor的rowcount属性时会返回-1”,sqlite就属于这种情况。
------------
rowcount返回的仅仅是受影响的行,select不会影响这些行。所有的SELECT
语句都不会有rowcount
-------------
另有不少文章说 cursor执行过fetchall() 一次之后 可以用 cursor.rowcount 获得,但我测试也是-1,那么是不是sqlite不行,但其他数据库可以呢?