查询结果在带有 SQLite 数据库的 C#.NET 中不正确
本文关键字:NET 不正确 数据库 SQLite 结果 查询 | 更新日期: 2023-09-27 18:36:22
我有一个用C#.NET和SQLite数据库实现的应用程序。我需要计算数据库表(水果)的列(状态)的一些值。表格如下所示。
Id B M status
1 10 101 2
2 11 102 2
3 11 103 0
4 12 104 2
5 13 105 2
6 13 105 2
7 14 106 2
8 14 106 2
9 14 106 2
10 14 106 2
我使用以下方法从表中提取值并显示输出。
public void CountingValues()
{
string strA, strB, strC;
double Total;
strA = countA();
strB = countB();
strC = countC();
MessageBox.Show(strA.ToString());
MessageBox.Show(strB.ToString());
MessageBox.Show(strC.ToString());
}
public string countA()
{
return GetData("SELECT COUNT(status) FROM fruit WHERE status = 2;");
}
public string countB()
{
return GetData("SELECT COUNT(status) FROM fruit WHERE status = 1;");
}
public string countC()
{
return GetData("SELECT COUNT(status) FROM fruit WHERE status = 0;");
}
private String GetData(String cmd)
{
String result = "";
SQLiteCommand command = new SQLiteCommand(connection);
command.CommandText = cmd;
SQLiteDataReader reader = command.ExecuteReader();
while (reader.Read())
{
result = reader[0].ToString();
}
reader.Dispose();
command.Dispose();
return result;
}
strA、strB 和 strC 的结果应分别为 9、0 和 1。但是,它显示 4、0 和 6。谁能告诉我这里出了什么问题?
尝试使用 select count(
*) 而不是 select count(status)。此外,如果您使用的是Visual Studio,请在"result = reader[0]"上放置断点。ToString()",然后查看正在填充的值。
每当我进行数据库调试时,我都会检查以确保数据表与我希望从 sql 查询接收的数据表相同。 在返回 DT 上放置一个断点,并确保获得与只在数据库上执行此查询相同的数据表结果。请确保将 sqlconnection 对象更改为您正在使用的类型。
public DataTable GetData()
{
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["BarManConnectionString"].ConnectionString);
conn.Open();
string query = "SELECT count(*) from fruit where status = 2";
SqlCommand cmd = new SqlCommand(query, conn);
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
return dt;
}