command.ExecuteScalar()取不到记录时,如何处理呢?
以下代码,我想获取书的库存数,但是,如果记录不存在,则取不到 册数,就会报错,
我应该如何写代码呢?
//获取库存
public int GetKuCun(string strywdh,string strsh,string strbc)
{
int iceshu;
iceshu = 0;
strsql = "select 册数 from cp_库存 where 业务单号='" + strywdh + "' and 书号='" + strsh + "' and 版次='" + strbc + "'"; command = new SqlCommand(strsql, mydb.conn);
iceshu = (int)command.ExecuteScalar();
return iceshu;
}
以下代码,我想获取书的库存数,但是,如果记录不存在,则取不到 册数,就会报错,
我应该如何写代码呢?
//获取库存
public int GetKuCun(string strywdh,string strsh,string strbc)
{
int iceshu;
iceshu = 0;
strsql = "select 册数 from cp_库存 where 业务单号='" + strywdh + "' and 书号='" + strsh + "' and 版次='" + strbc + "'"; command = new SqlCommand(strsql, mydb.conn);
iceshu = (int)command.ExecuteScalar();
return iceshu;
}
解决方案 »
- C++结构转换成C#怎么写(懂的进)谢谢
- 128码绘制问题请教
- 模拟器调试出现异常NotSupportedException: System.Drawing.Bitmap
- lookupedit控间问题
- 如何读INI文件中的设置信息啊?
- 我在使用VS.net的时候,代码写到“(”和“,”时,就不能动了 ?
- 如何得到方法的实参?
- public string extern int MessageBox (int hWnd,String text,
- 怎样显示年历,就是一年12个月全部按顺序列在同一页上?
- 请问这个编译错误是什么意思?warning MSB3884: 无法找到规则集文件“AllRules.ruleset”
- 求一函数(C#)
- 类的调用问题
记录查询不到,如何进行容错处理呢?
在这里,如果查不到记录,就应该返回 0
public int GetKuCun(string strywdh,string strsh,string strbc)
{
try
{
int iceshu;
iceshu = 0;
strsql = "select 册数 from cp_库存 where 业务单号='" + strywdh + "' and 书号='" + strsh + "' and 版次='" + strbc + "'"; command = new SqlCommand(strsql, mydb.conn);
iceshu = (int)command.ExecuteScalar();
}
catch{
return 0;
}
return iceshu;
}
//获取库存
public int GetKuCun(string strywdh,string strsh,string strbc)
{
int iceshu;
iceshu = 0;
strsql = "select 册数 from cp_库存 where 业务单号='" + strywdh + "' and 书号='" + strsh + "' and 版次='" + strbc + "'"; command = new SqlCommand(strsql, mydb.conn);
object temp = command.ExecuteScalar();
if(temp!=null)
{
iceshu=(int)temp;
}
return iceshu;
}
return val == null ? 0 : (int)val;
强制转换,没记录是肯定出错
protected static int ExecuSqlValue(string strSQL)
{ OleDbConnection myCn = new OleDbConnection(strconn);
OleDbCommand myCmd = new OleDbCommand(strSQL, myCn);
try
{
myCn.Open();
object r = myCmd.ExecuteScalar();
if (Object.Equals(r, null))
{
throw new Exception("value unavailable!"); }
else
{
return (int)r;
}
}
catch (OleDbException e)
{
throw new Exception(e.Message);
}
finally
{
myCmd.Dispose();
myCn.Close(); } }
public int GetKuCun(string strywdh,string strsh,string strbc)
{
int iceshu;
iceshu = 0;
strsql = "select 册数 from cp_库存 where 业务单号='" + strywdh + "' and 书号='" + strsh + "' and 版次='" + strbc + "'"; command = new SqlCommand(strsql, mydb.conn);
object temp = command.ExecuteScalar();
return iceshu==null?0:(int)iceshu;
}
正解 因为ExecuteScalar 返回的是一个object类型,所以如果你强制转换如果返回时null的话肯定报错。