获取查询的int值

 猫爱吃鱼了 发布于 2023-02-08 13:52

我有以下代码.

string connStr = String.Format("server=localhost;user id=root; password=1234;" + "database=Printermangement; pooling=false", "localhost", "root", "1234");
string Query = "select sum(Page_Printed) from printjobdetails where User_ID = 'MyProperty'GROUP by User_ID";
MySqlConnection conDataBase = new MySqlConnection(connStr);
MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase);

MessageBox.Show(Query);

我想sum从此查询中获取,但我无法弄清楚如何int在消息框中显示该值.我怎样才能做到这一点?

1 个回答
  • 您可以使用以下ExecuteScalar方法:

    // Prepare the command
    string connStr = ...
    string Query = "select sum(Page_Printed) from printjobdetails where User_ID = 'MyProperty' GROUP by User_ID";
    using(MySqlConnection conDataBase = new MySqlConnection(connStr))
    using(MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase))
    {
        // Execute the command and get the result
        var sum = (int)cmdDataBase.ExecuteScalar();
    
        // Display the result
        MessageBox.Show(string.Format("Sum: {0}", sum));
    }
    

    我还将您的命令和连接对象放在using块中.这将确保它们安全关闭,并且它们使用的任何非托管资源都将被正确处理.

    2023-02-08 13:53 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有