Exforsys

Home arrow Reviews arrow ODP.NET

ODP.NET - Handling Nulls when Working with OracleDataReader

Author: Packt Publishing     Published on: 5th Apr 2008    |   Last Updated on: 9th Apr 2008

ODP.NET - Handling Nulls when Working with OracleDataReader

When we work with OracleDataReader (or for that matter, even with data rows in a data table), we may come across nulls. The following is the efficient way to deal in with such scenarios:

Ads

Sample Code
  1. 'create connection to db
  2.         Dim cn As New OracleConnection("Data Source=xe; _
  3.              User Id=scott;Password=tiger")
  4.         Try
  5.         'create the command object
  6.         Dim cmd As New OracleCommand("SELECT comm FROM _
  7.                   emp WHERE empno="&Me.txtEmpno.Text, cn)
  8.     'open the connection from command
  9.     cmd.Connection.Open()
  10.     'create the data reader
  11.     Dim rdr As OracleDataReader = _  
  12.            cmd.ExecuteReader(CommandBehavior.CloseConnection)
  13.      'check if it has any rows
  14.      If rdr.HasRows Then
  15.         'read the first row
  16.                rdr.Read()
  17.              'extract the details
  18.          Dim result As Double = IIf(IsDBNull(rdr("comm")), _
  19.                     0, rdr("comm"))
  20.              MessageBox.Show("Commission: " & result)
  21.     Else
  22.          'display message if no rows found
  23.          MessageBox.Show("Not found")
  24.     End If
  25.     rdr.Dispose()
  26.     Catch ex As Exception
  27.     'display if any error occurs
  28.     MessageBox.Show("Error: " & ex.Message)
  29.     'close the connection if it is still open
  30.             If cn.State = ConnectionState.Open Then
  31.                 cn.Close()
  32.             End If
  33.     End Try
Copyright exforsys.com


Ads

You can observe that we are making use of the IIF function in Visual Basic.NET to make the inline comparison. We can also use the rdr.isDBNull method to achieve the same.



 
This tutorial is part of a ODP.NET tutorial series. Read it from the beginning and learn yourself.

ODP.NET

 

Comments