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

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

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

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

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

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

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.

rowcount返回的仅仅是受影响的行,select不会影响这些行。 所有的 SELECT语句都不会有 rowcount

Original: https://blog.csdn.net/bigcarp/article/details/114193423
Author: bigcarp
Title: python sqlite3 如何得到select 语句返回的记录集的行数?

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/817293/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球