【问题标题】:Query results are not correct in C#.NET with SQLite database使用 SQLite 数据库的 C#.NET 中的查询结果不正确
【发布时间】:2015-01-06 15:57:23
【问题描述】:

我有一个用 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。 谁能告诉我这里出了什么问题?

【问题讨论】:

  • 我建议您使用替代查询来显示 .NET 读取的数据库内容。我的猜测是您不小心附加到了错误的数据库。
  • 我的数据库是在应用程序运行时上传的。因此,没有错误的数据库连接的可能性。并且,您在谈论哪个替代查询?你能解释一下吗?
  • 我建议转储 SELECT * FROM fruit 的结果以用于诊断目的。
  • 我使用 SELECT * FROM fruit where status = 2. 但它显示的结果相同。
  • 那么您需要更改其余代码,以读取所有列和所有行...

标签: c# sql sqlite


【解决方案1】:

尝试使用 select count(*) 而不是 select count(status).. 另外,如果您使用的是 Visual Studio,请在“result = reader[0].ToString()”上放置一个断点,然后查看正在填充的值.

每当我进行数据库调试时,我都会检查以确保数据表与我期望从 sql 查询中收到的数据表相同。在 return dt 上放置一个断点,并确保您获得相同的数据表结果,就好像您只是在 db 上执行此查询一样。确保将 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;
}

【讨论】:

  • 它需要将数据从 DataTable 转换为 String 或 double,因为它返回 dt (DataTable)。我说的对吗?
  • 它显示错误 - 无法将“System.data.datatable”类型的对象转换为“system.IConvertible”类型。
  • 除了使用 DataTable 来计算值还有其他选择吗?
  • 我在DataTable中使用了你的方法,但结果是一样的。
  • 为了从 tdatatable 中获取值,您必须执行“dt.Rows[0][0].ToString()”,并且您不需要计算任何值,您已经返回该数据表对象中的计数
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多