我是 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/