MySQLDataReader retrieving Null value problem in c#

Viewed 24331

I am currently working on a C# project that will export MySQL Data. The export is for any database within the server so I am not going to know what fields and the data types that are in the table and I am not going to know if a field in the table allows null values or not.

During testing, I have found that the export is working fine but if the field allows null when the mysql data reader goes gets to the row which is null it displays an error SqlNullValueException, data is null.

I have tried doing if (reader.getString(field) == null) {} but it is still displaying the error.

How do I cope with Null values in the database.

Thanks for any help you can provide.

7 Answers

Expanding on @Summer-Time answer to include int columns:

using System.Data;

namespace MyApp
{

    public static class AppExtensions
    {
        public static string GetStringSafe(this IDataReader reader, int colIndex)
        {
            return GetStringSafe(reader, colIndex, string.Empty);
        }

        public static string GetIntAsStringSafe(this IDataReader reader, int colIndex, string defaultValue)
        {
            if (!reader.IsDBNull(colIndex))
                return reader.GetInt32(colIndex).ToString();
            else
                return defaultValue;
        }

        public static string GetIntAsStringSafe(this IDataReader reader, int colIndex)
        {
           return GetIntAsStringSafe(reader, colIndex, string.Empty);
        }


        public static string GetStringSafe(this IDataReader reader, int colIndex, string defaultValue)
        {
            if (!reader.IsDBNull(colIndex))
                return reader.GetString(colIndex);
            else
                return defaultValue;
        }

        public static string GetStringSafe(this IDataReader reader, string indexName)
        {
            return GetStringSafe(reader, reader.GetOrdinal(indexName));
        }

        public static string GetStringSafe(this IDataReader reader, string indexName, string defaultValue)
        {
            return GetStringSafe(reader, reader.GetOrdinal(indexName), defaultValue);
        }
    }
}
Related