我有这个代码,只要数据库中有匹配的值就可以使用:
public String GetDeptNameForDeptId(int deptId)
{
String deptName;
const string qry = "SELECT Name FROM Department WHERE Id = @deptID";
try
{
using (SQLiteConnection con = new SQLiteConnection(HHSUtils.GetDBConnection()))
{
con.Open();
SQLiteCommand cmd = new SQLiteCommand(qry, con);
cmd.Parameters.Add(new SQLiteParameter("deptID", deptId));
deptName = cmd.ExecuteScalar().ToString();
}
}
catch (Exception ex)
{
String msgInnerExAndStackTrace = String.Format(
"{0}; Inner Ex: {1}; Stack Trace: {2}", ex.Message, ex.InnerException, ex.StackTrace);
ExceptionLoggingService.Instance.WriteLog(String.Format("From Platypus.GetDeptNameForDeptId: {0}", msgInnerExAndStackTrace));
return "No matching value found"; //String.Empty;
}
return deptName;
}
但是,如果没有匹配(表中不存在deptId传入的Id值),则会发生NRE。是否存在优先失败的ExecuteScalar()替代方案?比如,简单地返回一个空字符串?
答案 0 :(得分:4)
而不是调用ToString
使用Convert.ToString
方法,而不是:
deptName = Convert.ToString(cmd.ExecuteScalar());
如果返回null
或DBNull.Value
,则返回空字符串。
答案 1 :(得分:2)
您可以查看结果:
var result = cmd.ExecuteScalar();
deptName = result == null ? "" : result.ToString();