I am using C#
Convert.ToDateTime(rdr["Termination_Date"])
rdr is defined as
OracleDataReader rdr = cmd.ExecuteReader();
The Termination_Date field in the table maybe null. How do I check if it's null and set a date like 01/01/0001
I am using C#
Convert.ToDateTime(rdr["Termination_Date"])
rdr is defined as
OracleDataReader rdr = cmd.ExecuteReader();
The Termination_Date field in the table maybe null. How do I check if it's null and set a date like 01/01/0001
On
Try this:
DateTime result = DateTime.MinValue;
int index = rdr.GetOrdinal("Termination_Date");
if(!rdr.IsDbNull(index))
result = rdr.GetDateTime(index);
Reference: OracleDataReader.GetDateTime(Int32) Method
An explanation: with DataReader classes, database nulls come across as the value DBNull.Value. You need to check for that value (there are various methods) before attempting to convert to the desired data type.
DateTime.MinValue is equivalent to 1/1/0001.
If you'd like to segue into using nullable variables rather than a "special value" to symbolize "no value", you could try this extention method (done from memory):
public static class Extensions {
public static T? GetNullableValue<T>(
this System.Data.Common.DbDataReader reader,
string columnName) where T : struct {
var ordIndex = reader.GetOrdinal(columnName);
if(reader.IsDbNull(ordIndex))
return null;
else
return (T?) reader.GetValue(ordIndex)
}
}
If you have to access the column by name, you can compare against
DBNull.Valuewith something like a ternary statement to pick betweenDateTime.MinValue(1/1/0001) and the result of converting the non-null value.You can do this more concisely with
OracleDataReader.IsDBNull()andOracleDataReader.GetDateTime()if you know the column index (assume that our desired value is the first column in the result).