打开数据集,计数记录并将数字返回变量的最快方法

And*_*yDB 1 c# sqlite wpf

我是C#/ WPF / SQLite的新手,并且创建了一个表单,该表单需要显示多个计算(来自两个不同的表)。我想知道你们认为最快的方法是(如果有人可以提供代码的粗略指南,那将是很大的帮助)。

这有点粗糙(并且不能完全正常工作),但是这里是:

    string cs = ClsVariables.StrDb;
    using(SQLiteConnection con = new SQLiteConnection(cs))
    {
        con.Open();
        string stm = "SELECT [ID] FROM tblActivities WHERE [Activity]='Sleeping'";
        using (SQLiteCommand cmd = new SQLiteCommand(stm, con))
        {
            //I'm guessing this is where I need count the number of rows (but haven't figure that bit out just yet
        }
        con.Close();   
     }
Run Code Online (Sandbox Code Playgroud)

Ste*_*eve 5

SQL 的聚合函数COUNT可以解决您的问题,但是在C#代码上,您不需要用表填充数据集,然后对找到的行进行计数。您都不需要SQLiteDateReader,因为当您期望结果仅是一行且只有一列时,您可以使用ExecuteScalar

string cmdText = "SELECT COUNT(ID) FROM tblActivities WHERE [Activity] = 'Sleeping'";
using(SQLiteConnection con = new SQLiteConnection(cs))
using(SQLiteCommand cmd = new SQLiteCommand(cmdText, con))
{
    con.Open();
    int count = Convert.ToInt32(cmd.ExecuteScalar());
    Console.WriteLine("You have " + count.ToString() + " records sleeping");
}
Run Code Online (Sandbox Code Playgroud)

关于ExecuteScalar的最后说明。它可能返回NULL,但在您的情况下(COUNT返回零或数字> 0),这是不可能的,因此我不检查返回值是否为null,而是直接将其转换为整数