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

前端 未结 11 2170
生来不讨喜
生来不讨喜 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:04

    Here is my full implementation in a static method. You should be able to plug this into your class (replace _STR_DB_FILENAME & STR_TABLE_NAME with your database file name and table name).

        /// 
        /// Returns a count of the number of items in the database.
        /// 
        /// 
        public static int GetNumberOfItemsInDB()
        {
            // Initialize the count variable to be returned
            int count = 0;            
    
            // Start connection to db
            using (SqliteConnection db =
                new SqliteConnection("Filename=" + _STR_DB_FILENAME))
            {
                // open connection
                db.Open();
    
                SqliteCommand queryCommand = new SqliteCommand();
                queryCommand.Connection = db;
    
                // Use parameterized query to prevent SQL injection attacks
                queryCommand.CommandText = "SELECT COUNT(*) FROM " + _STR_TABLE_NAME;
                // Execute command and convert response to Int
                count = Convert.ToInt32(queryCommand.ExecuteScalar());
                // Close connection
                db.Close();
            }
            // return result(count)
            return count;
        }
    

    Note: To improve performance, you can replace '' in "SELECT COUNT()…." with the column name of the primary key in your table for much faster performance on larger datasets.

提交回复
热议问题