我正在尝试使用基本ado.net过程计算数据库表中某些int条目的平均值,但得到一个错误,指出该转换无效。计算字段条目的平均值
try
{
int average;
string conn = @"Provider=Microsoft.Jet.OleDb.4.0;
Data Source=BookRateInitial.mdb";
OleDbConnection connection = new OleDbConnection(conn);
OleDbCommand cmd = connection.CreateCommand();
cmd.CommandText = @"SELECT AVG(rating) FROM bookRated WHERE title = 'the informers'";
connection.Open();
average = (int)cmd.ExecuteScalar();
Console.WriteLine("The average is thus {0}", average);
connection.Close();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
这是计算数据库中一组条目平均值的正确方法吗?
亲切的问候
您得到了什么类型的异常。当您直接在数据库上运行查询时会发生什么?你也有连接泄漏。把连接关闭在最后或使用“使用”(http://stackoverflow.com/questions/4085466/what-is-using-connection-in-the-code)。我还建议使用存储过程,而不是将代码放在代码 – Ivo 2011-04-27 13:16:52
中。错误可能是因为您的平均值有小数位,所以它无法转换为int。您需要将其舍入到无小数位,或截断它。 – David 2011-04-27 13:18:10