获取查询的int值

时间:2013-12-23 19:54:50

标签: c# database winforms int

我有以下代码。

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值。我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:9)

您可以使用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块中。这将确保它们安全关闭,并且它们使用的任何非托管资源都将被妥善处理。

答案 1 :(得分:1)

此示例来自Jan Bodnar的this blog(非常有用),略微编辑以使用ExecuteScalar()方法执行查询。

using System;
using MySql.Data.MySqlClient; 

public class Example
{

    static void Main() 
    {
        string cs = @"server=localhost;userid=user12;
            password=34klq*;database=mydb";

        MySqlConnection conn = null;
        MySqlDataReader rdr = null;

        try 
        {
            conn = new MySqlConnection(cs);
            conn.Open();

            string stm = "SELECT * FROM Authors";
            MySqlCommand cmd = new MySqlCommand(stm, conn);

            int sum = (int)cmd.ExecuteScalar();
            Console.WriteLine(sum);

        } catch (MySqlException ex) 
        {
            Console.WriteLine("Error: {0}",  ex.ToString());

        } finally 
        {

            if (conn != null) 
            {
                conn.Close();
            }

        }
    }
}