使用cmd.ExecuteScalar()方法:
decimal average = (decimal) cmd.ExecuteScalar();
cmd.ExecuteNonQuery();
只返回影響的行數,其中,你想要的是讀取結果一套SELECT
聲明。
我也從SELECT
聲明中刪除了USE [DB_SACC]
,因爲您在連接字符串中定義了數據庫名稱。
編輯
您的代碼應該是這樣的:
string textt = "SELECT AVG (Total_Divida) FROM t_pagamentos";
cmd.CommandText = textt;
connection.Open();
cmd.Connection = connection;
cmd.CommandType = CommandType.Text;
decimal average = (decimal) cmd.ExecuteScalar();
if (textt == null)
{
MessageBox.Show("nothing");
}
else
{
TextBox3.Text = average.ToString();
}
編輯2:
try
{
string textt = "SELECT AVG (Total_Divida) FROM t_pagamentos";
cmd.CommandText = textt;
connection.Open();
cmd.Connection = connection;
cmd.CommandType = CommandType.Text;
decimal average = (decimal)cmd.ExecuteScalar();
TextBox3.Text = average.ToString();
}
catch(Exception ex)
{
// log your exception here...
MessageBox.Show("nothing");
}
編輯3:
在你最近的評論光試試這個
string connectionString = "Data Source=localhost; Initial Catalog=DB_SACC; User id=sa Password=1234;";
decimal? average;
try
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand())
{
string textt = "SELECT AVG (Total_Divida) AS 'AVG_DIVIDA' FROM t_pagamentos";
cmd.CommandText = textt;
connection.Open();
cmd.Connection = connection;
cmd.CommandType = CommandType.Text;
using (DataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
average = decimal.parse(reader["AVG_DIVIDA"].ToString());
break;
}
}
}
}
TextBox3.Text = average.HasValue ? average.ToString() : "Unknown error occurred";
}
catch (Exception ex)
{
MessageBox.Show("Unable to retrieve the average, reason: " + ex.Message);
}
注:使用的DataReader從數據庫是不優選得到的只是單一值。我提出這個建議是因爲你在評論中提到的錯誤。
如果您正在獲取任何SQL異常,請嘗試在SQL Server上將此語句作爲獨立測試運行。
USE DB_SACC
GO
SELECT AVG (Total_Divida) AS 'AVG_DIVIDA' FROM t_pagamentos
GO
如果在執行T-SQL語句時仍然遇到任何錯誤,請將其作爲另一個問題發佈。
提示:你正在執行一個查詢'cmd.ExecuteNonQuery()' –
http://stackoverflow.com/questions/5349114/executenonquery – mayk
使用'ExecuteScalar()'將其存儲在某個對象中,然後訪問它 –