嗨,我在C#中工作,我想要一个计算平均值的按钮一些数字。
这是我的代码:
private void button5_Click(object sender, EventArgs e) { connect.Open(); string avg= "SELECT AVG(number) FROM info WHERE number = @number"; SqlCommand command= new SqlCommand(avg, connect); SqlDataAdapter da = new SqlDataAdapter(command); textBox8.Text = ; //I dont know what should I write here. connect.Close();
我想通过按钮在文本框中显示数字的平均值。怎样我该怎么办?你能帮我吗?
编辑
我解决了这个问题:
private void button5_Click(object sender, EventArgs e)
{
connect.Open();
SqlCommand command= new SqlCommand("SELECT AVG(number) FROM info", connect);
SqlDataReader dr = command.ExecuteReader();
SqlDataAdapter da = new SqlDataAdapter(command);
if (dr.Read())
{
textBox8.Text = dr[0].ToString();
}
connect.Close();
}
}
}
代码不仅缺少查询结果的设置,还缺少执行查询所需的其他部分。
private void button5_Click(object sender, EventArgs e)
{
connect.Open();
string avg= "SELECT AVG(number) FROM info WHERE number = @number";
SqlCommand command= new SqlCommand(avg, connect);
// You need to add a parameter for @number and set its value
command.Parameters.Add(@number, SqlDbType.Int).Value = valueForNumber;
// Now you need to execute the command to get back the average value
object result = command.ExecuteScalar();
// Finally you set the textbox with a conversion in string of the returned value
// but also check if there is really a return value
if(result != null)
textBox8.Text = result.ToString();
else
textBox8.Text = "Number Not found!";
connect.Close();
}
但该代码还有其他问题
当您处理一次性物品时,您应该牢记危险信号。一次性物品";通常";包含应尽快释放的资源
连接和命令就是此类对象。在原始代码中,连接似乎是一个全局对象。像这样的代码应该避免这种情况
private void button5_Click(object sender, EventArgs e)
{
using(SqlConnection cnn = new SqlConnection(getTheConnectionString())
{
connect.Open();
string avg= "SELECT AVG(number) FROM info WHERE number = @number";
using(SqlCommand command= new SqlCommand(avg, cnn))
{
// You need to add a parameter for @number and set its value
command.Parameters.Add("@number", SqlDbType.Int).Value = valueForNumber;
// Now you need to execute the command to get back the average value
object result = command.ExecuteScalar();
// Finally you set the textbox with a conversion in string of the returned value
// but also check if there is really a return value
if(result != null)
textBox8.Text = result.ToString();
else
textBox8.Text = "Number Not found!";
} // End using => SqlCommand disposed...
} // End using => SqlConnection closed and disposed
}
using块跟踪可丢弃对象,并确保当代码退出using块时,即使在块内部发生异常时,也能正确处理这些对象。