2013-12-23 117 views
2

我有以下代碼。獲取查詢的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值在消息框中顯示。我怎樣才能做到這一點?

+4

'MessageBox.Show(Query);'顯示查詢,而不是結果。 –

回答

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

本示例來自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(); 
      } 

     } 
    } 
} 
+1

爲什麼'ExecuteReader'? OP只需要一個值; 'executablecalar'是需要的。 – Rahul

+0

@Rahul是真正的固定代碼示例。謝謝。 –