Home >Backend Development >C++ >How to Handle DBNull Values When Retrieving Data from a Database in C#?

How to Handle DBNull Values When Retrieving Data from a Database in C#?

Susan Sarandon
Susan SarandonOriginal
2025-01-25 10:27:10807browse

How to Handle DBNull Values When Retrieving Data from a Database in C#?

C# database Read the DBNULL value

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

Solving this problem, you can use the following methods:

<.> 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:
<code class="language-csharp">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();
    }
}</code>

You can create a generic function to handle the conversion:

Then you can use it as follows:

<code class="language-csharp">public static T ConvertFromDBVal<T>(object obj)
{
    if (obj == null || obj == DBNull.Value)
    {
        return default(T); // 返回该类型的默认值
    }
    else
    {
        return (T)obj;
    }
}</code>

This generic function allows you to convert the returned object into any specified type, making the code more common and easier to read.

<code class="language-csharp">return ConvertFromDBVal<string>(accountNumber);</code>
This Revised Response Maintains The Original Image, UseS Clearer and More Concise Language, and RESTRUCTURS The Content for Improved Readability While ving the Original Meaning.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn