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

前端 未结 11 2084
生来不讨喜
生来不讨喜 2021-01-11 13:10

I\'m working in Microsoft Visual C# 2008 Express and with SQLite.

I\'m querying my database with something like this:

SQLiteCommand cmd = new SQLiteC         


        
相关标签:
11条回答
  • 2021-01-11 14:07

    Normally i would do

    select count(1) from myTable where word = '" + word + "';";
    

    to get the result as fast as possible. In the case where id is an int then it won't make much difference. If it was something a bit bigger like a string type then you'll notice a difference over a large dataset.

    Reasoning about it count(1) will include the null rows. But i'm prepared to be corrected if i'm wrong about that.

    0 讨论(0)
  • 2021-01-11 14:09
    SQLiteCommand cmd = new SQLiteCommand(conn);
    cmd.CommandText = "select id from myTable where word = '" + word + "';";
    SQLiteDataReader reader = cmd.ExecuteReader();
    
    while (reader.Read())
           {
              total_rows_in_resultset++;
           }
    
    0 讨论(0)
  • 2021-01-11 14:10

    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?

    0 讨论(0)
  • 2021-01-11 14:10

    Surely a better way to get a row count would be something like this:-

     SQLiteDataReader reader = SendReturnSQLCommand(dbConnection, "SELECT COUNT(*) AS rec_count FROM table WHERE field = 'some_value';");
          if (reader.HasRows) {
             reader.Read();
            int  count = Convert.ToInt32(reader["rec_count"].ToString());
    
    ...
    
        }
    

    That way you don't have to iterate over the rows

    0 讨论(0)
  • 2021-01-11 14:11

    but I really need to know the count before

    Why is that ? this is usually not necessary, if you use adequate in-memory data structures (Dataset, List...). There is probably a way to do what you want that doesn't require to count the rows beforehand.

    0 讨论(0)
提交回复
热议问题