试图从的ExecuteScalar获得价值时,铸造例外() [英] Casting Exception when trying to get value from ExecuteScalar()
问题描述
在下面的代码中,语句1抛出铸造例外。我很奇怪,为什么不是它拆箱?结果
语句2工作正常,但我想知道为什么第一个是错的?
使用(IDbCommand的命令= connection.CreateCommand())
{
command.CommandText =的String.Format(SELECT COUNT(1)FROM {0}中,TableName);
诠释计数=(int)的command.ExecuteScalar(); //声明1
}
//诠释计数= Convert.ToInt32(command.ExecuteScalar()); //声明2
叹息,执行标量返回长/ Int64的,看到你写的SQL命令你知道回报淡水河谷将是一个计算的整数(SELECT COUNT(...,也可以选择MAX(...
忽略其他方面的建议,你需要的是一个演员。(NO这些命令将永远不会返回一个字符串,如42)
诠释计数=(INT)(长)command.ExecuteScalar();
或担心大量
长数=(长)command.ExecuteScalar();
除非,出于某种奇怪的原因你没有在SQL语句控制执行的问题为什么用转换或装箱/拆箱$ b复杂$ b好格雷夫人,KISS,就用代码膨胀,......,只是回答问题。
In the below code, the statement 1 throws casting exception. I am wondering why isnt it unboxing?
The statement 2 works fine but I want to know why the first one is wrong?
using (IDbCommand command = connection.CreateCommand())
{
command.CommandText = string.Format("SELECT COUNT(1) FROM {0}", tableName);
int count = (int)command.ExecuteScalar(); //statement 1
}
//int count = Convert.ToInt32(command.ExecuteScalar()); //statement 2
Sigh, execute scalar returns a long/int64, seeing as you wrote the SQL command you know the return vale is going to be a computed whole number (SELECT COUNT(..., also SELECT MAX(...
Ignore the other advice, all you need is a cast. (NO these commands will never return a string, i.e. "42")
int count = (int)(long)command.ExecuteScalar();
or if worried about large numbers
long count = (long)command.ExecuteScalar();
Unless, for some weird reason you don't have control over the SQL statement being executed why complicate matters with Convert, or boxing/unboxing. Good greif people, K.I.S.S., down with code bloat, ... and just answer the question.
这篇关于试图从的ExecuteScalar获得价值时,铸造例外()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!