c# - 打开数据集、计算记录并将数字返回给变量的最快方法

标签 c# wpf sqlite

我是 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();   
     }

最佳答案

聚合函数COUNT SQL 可以解决你的问题,但在 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");
}

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

关于c# - 打开数据集、计算记录并将数字返回给变量的最快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22883543/

相关文章:

python - sqlite3根据纪元时间获取数据

c# - AutoMapper: 'AutoMapper.AutoMapperMappingException' 类型的异常发生在 AutoMapper.dll 中,但未在用户代码中处理

用于平铺 ListView 的 WPF 工具包

mysql - 将列别名分配给条件在 sqlite 中不起作用的地方

c# - 第一个敏捷项目——我应该先写什么?

wpf - 使用触发器在鼠标悬停时设置文本 block 前景

android - Sqlite 数据库更新触发 Service 通过 Content Observer 更新

C# 如何在文本框具有焦点时通过按 Enter 来单击按钮?

c# - 套接字错误 10054 : Error Handling Issue

c# - Visual Studio 错误 CS0433 : The type exists in both. .. (Unity-Accord.net)