tags:

views:

2182

answers:

5

I want to get the number of selected rows as well as the selected data. At the present I have to use two sql statements: one is select * from XXX where XXX; the other is select count(*) from XXX where XXX; Can it be realised with a single sql string?

I've checked the source code of sqlite3, and I found the function of sqlite3_changes(). But the function is only useful when the database is changed (after insert, delete or update).

Can anyone help me with this problem? Thank you very much!

A: 

Once you already have the select * from XXX results, you can just find the array length in your program right?

Swaroop C H
I can. But only until I go through all the result rows. I want to get the count as quickly as possible
In that case, I guess running two SQL queries really is the simplest solution.
Swaroop C H
A: 

You could combine them into a single statement:

select count(*), * from XXX where XXX

or

select count(*) as MYCOUNT, * from XXX where XXX
dalle
this only returns row count and only the last row.
idursun
yes, I can't get the exact result rows using this method.
A: 

If you use sqlite3_get_table instead of prepare/step/finalize you will get all the results at once in an array ("result table"), including the numbers and names of columns, and the number of rows. Then you should free the result with sqlite3_free_table

Zydeco
Thank you. I will have a try.
+2  A: 

SQL can't mix single-row (counting) and multi-row results (selecting data from your tables). This is a common problem with returning huge amounts of data. Here are some tips how to handle this:

  • Read the first N rows and tell the user "more than N rows available". Not very precise but often good enough. If you keep the cursor open, you can fetch more data when the user hits the bottom of the view (Google Reader does this)

  • Instead of selecting the data directly, first copy it into a temporary table. The INSERT statement will return the number of rows copied. Later, you can use the data in the temporary table to display the data. You can add a "row number" to this temporary table to make paging more simple.

  • Fetch the data in a background thread. This allows the user to use your application while the data grid or table fills with more data.

Aaron Digulla
A: 

the get table option is ok if you only have a few rows, not the best if you have hundreds of millions....