"Paul Clement" <UseAdddressAtEndofMessage (AT) swspectrum (DOT) com> skrev i en
meddelelse news:23fl515evsa7l8gn8hlb8u7dnoj94uietc (AT) 4ax (DOT) com...
Quote:
On Mon, 11 Apr 2005 10:44:05 +0200, "Peter Kirk" <pk (AT) alpha-solutions (DOT) dk
wrote:
¤ Hi
¤
¤ I am using OleDbDataReader to get some data from a database. I have
noticed
¤ I get an exception if one of the database columns contains a null value.
¤ Sure enough, the documentation says I have to call IsDbNull first, to
avoid
¤ an error.
¤
¤ Can this be right? Is it possible just to call GetString, for example,
and
¤ get a null if the database value is null? What is the rationale behind
this?
¤ It seems to mean that all my "Gets" require I write a test for null
¤ values...
At what point to you get the error? Code example? |
Hi, below is some c# code which retrieves a list of "Tasktype" objects.
Tasktype has two attributes: name & description.
There is a row in the database which has description = null.
This code works, because I have added the check for a null value when I
extract the data from the resultset:
t.Description = rs.IsDBNull(1) ? null : rs.GetString(1);
Extraction from the resultset will fail on the null data if I just have:
t.Description = rs.GetString(1);
// Retrieves a list of Tasktype objects.
public IList GetAllTasktypes()
{
OleDbCommand myCommand = null;
try
{
string mySelectQuery = "SELECT Name, Description FROM t_Tasktype
ORDER BY Name";
myCommand = new OleDbCommand(mySelectQuery);
myCommand.Connection = GetConnection();
OleDbDataReader resultSet = myCommand.ExecuteReader();
IList tasktypes = null;
if ( (resultSet!=null) && (resultSet.HasRows))
{
tasktypes = new ArrayList();
while (resultSet.Read())
{
Tasktype t = new Tasktype();
t.Name = rs.IsDBNull(0) ? null : rs.GetString(0);
t.Description = rs.IsDBNull(1) ? null : rs.GetString(1);
tasktypes.Add(t);
}
}
return tasktypes;
}
finally
{
if ( (myCommand!=null) && (myCommand.Connection!=null))
CloseConnection(myCommand.Connection);
}
}
private OleDbConnection GetConnection()
{
string myConnectionString =
ConfigurationSettings.AppSettings.Get("ITTSDBConne ctionString");
OleDbConnection myConnection = new
OleDbConnection(myConnectionString);
myConnection.Open();
return myConnection;
}
Thanks,
Peter