我有以下代码.
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
在消息框中显示该值.我怎样才能做到这一点?
您可以使用以下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
块中.这将确保它们安全关闭,并且它们使用的任何非托管资源都将被正确处理.