I've got this code, which works as long as there is a matching value in the database:
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 TestHHSDBUtils.GetDeptNameForDeptId: {0}", msgInnerExAndStackTrace));
return "No matching value found"; //String.Empty;
}
return deptName;
}
However, if there is no match (the Id val passed in as deptId does not exist in the table), an NRE occurs. Is there an alternative to ExecuteScalar() that will fail gracefully? Such as, simply return an empty string?
Aucun commentaire:
Enregistrer un commentaire