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:
Sample Code
'create connection to db
Dim cn As New OracleConnection("Data Source=xe; _
User Id=scott;Password=tiger")
Try
'create the command object
Dim cmd As New OracleCommand("SELECT comm FROM _
emp WHERE empno="&Me.txtEmpno.Text, cn)
'open the connection from command
cmd.Connection.Open()
'create the data reader
Dim rdr As OracleDataReader = _
cmd.ExecuteReader(CommandBehavior.CloseConnection)
'check if it has any rows
If rdr.HasRows Then
'read the first row
rdr.Read()
'extract the details
Dim result As Double = IIf(IsDBNull(rdr("comm")), _
0, rdr("comm"))
MessageBox.Show("Commission: " & result)
Else
'display message if no rows found
MessageBox.Show("Not found")
End If
rdr.Dispose()
Catch ex As Exception
'display if any error occurs
MessageBox.Show("Error: " & ex.Message)
'close the connection if it is still open
If cn.State = ConnectionState.Open Then
cn.Close()
End If
End Try
Copyright exforsys.com
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.