How do I count the number of rows returned in my SQLite reader in C#?

The DataReader runs lazily, so it doesn't pick up the entirety of the rowset before beginning. This leaves you with two choices:

  1. Iterate through and count
  2. Count in the SQL statement.

Because I'm more of a SQL guy, I'll do the count in the SQL statement:

cmd.CommandText = "select count(id) from myTable where word = '" + word + "';";
cmd.CommandType = CommandType.Text;
int RowCount = 0;

RowCount = Convert.ToInt32(cmd.ExecuteScalar());

cmd.CommandText = "select id from myTable where word = '" + word + "';";
SQLiteDataReader reader = cmd.ExecuteReader();

//...

Note how I counted *, not id in the beginning. This is because count(id) will ignore id's, while count(*) will only ignore completely null rows. If you have no null id's, then use count(id) (it's a tad bit faster, depending on your table size).

Update: Changed to ExecuteScalar, and also count(id) based on comments.


Do a second query:

cmd.CommandText = "select count(id) from myTable where word = '" + word + "';";
cmd.CommandType = CommandType.Text;
SQLiteDataReader reader = cmd.ExecuteReader();

Your reader will then contain a single row with one column containing the number of rows in the result set. The count will have been performed on the server, so it should be nicely quick.


What you request is not feasible -- to quote Igor Tandetnik, my emphasis:

SQLite produces records one by one, on request, every time you call sqlite3_step. It simply doesn't know how many there are going to be, until on some sqlite3_step call it discovers there are no more.

(sqlite3_step is the function in SQLite's C API that the C# interface is calling here for each row in the result).

You could rather do a "SELECT COUNT(*) from myTable where word = '" + word + "';" first, before your "real" query -- that will tell you how many rows you're going to get from the real query.


If you are only loading an id column from the database, would it not be easier to simply load into a List<string> and then work from there in memory?

Tags:

C#

Sqlite