-1

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 Platypus.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?

4

2 回答 2

4

而不是调用ToStringuseConvert.ToString方法,例如:

 deptName = Convert.ToString(cmd.ExecuteScalar());

null如果返回或返回,这将返回空字符串DBNull.Value

于 2015-02-10T17:45:04.773 回答
2

您可以检查结果:

var result = cmd.ExecuteScalar();
deptName = result == null ? "" : result.ToString();
于 2015-02-10T17:40:36.080 回答