C#MySQL总和查询到标签 [英] c# mysql sum query to label

查看:63
本文介绍了C#MySQL总和查询到标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试做一些我觉得在宏伟的事情中很简单的事情,但是我显然缺少了一些东西.我拥有的是一个简单的名为"localcollection"的数据库.我想做的是总结一个名为"purprice"的列的美元金额,并将其设置为标签的文本(label4).在过去的几天中,我一直在寻找各种代码变体,这些变体提出了实现这一目标的不同方法.我的大部分挖掘工作都表明我想使用ExecuteScalar.我一直在摸索的代码如下.

I'm trying to do something I feel is quite simple in the grand scheme of things, however I'm clearly missing something. What I have is a simple database named 'localcollection'. What I would like to do is sum up the dollar amount of a column named 'purprice', and setting it as the text of a label (label4). I've been finding variants of code throughout the last couple days that suggest different ways of achieving this. The majority of my digging suggest that using ExecuteScalar is what I want to do. The code that I've been fumbling with follows.

SqlCeConnection myconn = new SqlCeConnection(Properties.Settings.Default.localbotdbConnectionString);
myconn.Open();

{
    string result = "select sum(purprice) from localcollection";
    SqlCeCommand showresult = new SqlCeCommand(result, myconn);

    label4.Text = showresult.ExecuteScalar().ToString();
    myconn.Close();
}

其他人建议使用SqlCeReader.只要其中一个有效,我对他们中的任何一个都是公正的,而且我显然错过了一些东西(我自己的错).我试图做的读者解释是:

Others suggest using the SqlCeReader. I'm impartial to either of them, as long as one of them works, and I am clearly missing something (fault of my own). The reader rendition that I was trying to make work is:

SqlCeCommand cmd = new SqlCeCommand("select sum(purprice) from localcollection");
SqlCeDataReader reader = cmd.ExecuteReader();
while(reader.Read())
{
    label4.Text = reader.GetString(0);
}
myconn.Close();

建设性的建议表示赞赏.谢谢

Constructive advice appreciated. Thank you

推荐答案

我会对您的代码进行一些修改,因为一方面,您没有正确地处置对象,同时您还说您在按钮click方法中拥有了它.我会从那里得到它,并使它成为自己的功能.

I would do some modifications to your code because for one thing your are not properly disposing of your objects, also you stated that you have it in the button click method which I would get that out of there and make this its own function.

private string performSQL() 
{
   string result = "select sum(purprice) from localcollection";
   using (SqlCeConnection myconn = new SqlCeConnection("ConnectionString"))
   using (SqlCeCommand showresult = new SqlCeCommand(result, myconn))
   {
      try
      {
          myconn.Open();
          return showresult.ExecuteScalar().ToString();

      }catch(System.Exception ex)
      {
          MessageBox.Show(ex.ToString());
          // or log exception how ever you prefer
      }finally
      {
          //the finally ensures your connection gets closed
          myconn.Close();
      }
   }
   return "";
}

这篇关于C#MySQL总和查询到标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆