When retrieved data from the database, the return value may encounter a situation with null or dbnull. This may cause errors when trying to convert values to specific types (such as string).
The following code fragment demonstrates how to solve this problem: the original code attempt to directly convert the
method of the method into a string, causing an error. "Unable to convert the type of" System.dbnull 'to the type' type '" System.string '". ExecuteScalar
<.> 1. Use a vacant value check for explicit type conversion:
Before trying to enforce the conversion, you can explicitly check DBNULL. The following is the code after modified:
<.> 2. Use generic functions for type conversion:
public string GetCustomerNumber(Guid id) { object accountNumber = DBSqlHelperFactory.ExecuteScalar(connectionStringSplendidCRM, CommandType.StoredProcedure, "spx_GetCustomerNumber", new SqlParameter("@id", id)); if (accountNumber is DBNull) { return string.Empty; // 返回空字符串 } else { return accountNumber.ToString(); } }
You can create a generic function to handle the conversion:
Then you can use it as follows:
public static T ConvertFromDBVal<T>(object obj) { if (obj == null || obj == DBNull.Value) { return default(T); // 返回该类型的默认值 } else { return (T)obj; } }
This generic function allows you to convert the returned object into any specified type, making the code more common and easier to read.
return ConvertFromDBVal<string>(accountNumber);
The above is the detailed content of How to Handle DBNull Values When Retrieving Data from a Database in C#?. For more information, please follow other related articles on the PHP Chinese website!