使用字符串结果返回值= Command.ExecuteScalar()时,结果返回null出现错误 [英] Return value using String result=Command.ExecuteScalar() error occurs when result returns null
问题描述
我要来从数据库它运作良好低于code第一行第一单元格值。但是,当没有结果发现它抛出异常。
如何处理与的DBNull
。结果
我应该改变我的查询?其中一些返回值,如果他们没有记录?
的 System.NullReferenceException:未将对象引用设置到对象的实例的
code:
公共字符串absentDayNo(日期时间SDATE,日期EDATE,串idemp)
{
字符串结果=0;
字符串更改为MyQuery =SELECT COUNT(idemp_atd)absentDayNo从td_atd其中;
更改为MyQuery + ='+ SDATE +和+ EDATE +之间absentdate_atd';
更改为MyQuery + =和idemp_atd ='+ idemp +'GROUP BY idemp_atd; CMD的SqlCommand =新的SqlCommand(更改为MyQuery,康涅狄格州);
conn.Open();
当他们没有数据/结果发生//System.NullReferenceException
。字符串的getValue = cmd.ExecuteScalar()的ToString();
如果(的getValue!= NULL)
{
结果= getValue.ToString();
}
conn.Close();
返回结果;
}
有没有必要继续呼叫的ToString()
为的getValue
已经是一个字符串。
除此之外的是,这条线可能可能是你的问题:
字符串的getValue = cmd.ExecuteScalar()的ToString()。
如果没有行 .ExecuteScalar
将返回空
,所以你需要做一些检查。
例如:
VAR firstColumn = cmd.ExecuteScalar();如果(firstColumn!= NULL){
结果= firstColumn.ToString();
}
I want to fetch 1st row 1st cell value from database it works well with below code . But when there is no result found it throws Exception.
How to handle with DBNull
.
Should i change my query ? which return some value if theirs no record ?
System.NullReferenceException: Object reference not set to an instance of an object.
Code:
public string absentDayNo(DateTime sdate, DateTime edate, string idemp)
{
string result="0";
string myQuery="select COUNT(idemp_atd) absentDayNo from td_atd where ";
myQuery +=" absentdate_atd between '"+sdate+"' and '"+edate+" ";
myQuery +=" and idemp_atd='"+idemp+"' group by idemp_atd ";
SqlCommand cmd = new SqlCommand(myQuery, conn);
conn.Open();
//System.NullReferenceException occurs when their is no data/result
string getValue = cmd.ExecuteScalar().ToString();
if (getValue != null)
{
result = getValue.ToString();
}
conn.Close();
return result;
}
There is no need to keep calling .ToString()
as getValue
is already a string.
Aside that, this line could possibly be your problem:
string getValue = cmd.ExecuteScalar().ToString();
If there are no rows .ExecuteScalar
will return null
so you need to do some checking.
For instance:
var firstColumn = cmd.ExecuteScalar();
if (firstColumn != null) {
result = firstColumn.ToString();
}
这篇关于使用字符串结果返回值= Command.ExecuteScalar()时,结果返回null出现错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!