python sqlite3 如何得到select 语句返回的记录集的行数?

官方文档有cursor.rowcount ,但通常返回值是-1。

查询相关资料,得到答案如下:

没有可以直接得到行数的函数。sqlite事先不知道行数,遍历时才逐行返回。--->遍历完才知道的话,是否意味着并没有一次过将全部数据返回写入内存?

可以用 : result=cursor.fetchall()  然后 count=len(result) 获取。

或者执行一次 select count(*) from x where y 然后 fetchone 获取

 

参考:https://stackoverflow.com/questions/3890517/how-do-i-use-num-rows-function-in-the-mysqldb-api-for-python

 

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不行,但其他数据库可以呢?

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值