我正在尝试使用基本的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);
}
这是计算数据库中一组条目平均值的正确方法吗?
亲切的问候
答案 0 :(得分:0)
尝试
object result = cmd.ExecuteScalar();
if (! (result is DBNull))
{
average = Convert.ToInt32(result);
}
顺便说一下,不应该是浮动/双倍平均值吗?
答案 1 :(得分:0)
你可以替换
average = (int)cmd.ExecuteScalar();
with:
Reader = cmd.ExecuteReader();
while (Reader.Read())
{
average = Reader.GetInt32(0);
}
答案 2 :(得分:0)
尝试转换/转换为十进制。 ;)
类似这样的事情
try { return Convert.ToDecimal(cmd.ExecuteScalar()); }
catch (Exception) { throw; }
答案 3 :(得分:0)
错误消息说明错了。结果是DBNull或它不是Int32。如果您确定结果类型是Int32,请使用:
var result = cmd.ExecuteScalar();
average = result != DBNull.Value ? (int) result : 0;