alt
Advertisement
Sponsored links
Online Training
Career Series
Exforsys
Exforsys arrow Tutorials arrow ODP.NET arrow ODP.NET - Handling Nulls when Executing with ExecuteScalar
Site Search


ODP.NET - Handling Nulls when Executing with ExecuteScalar

ODP.NET - Handling Nulls when Executing with ExecuteScalar

The most important issue to remember is that ExecuteScalar simply returns an object type of data. The object refers to any data type within .NET. If the data type of your variable matches with the type of object returned by ExecuteScalar, an implicit (automatic) conversion takes place.

There would not be a problem as long as the data types match. However, it would be a problem if the result is NULL. Let us have an example that accepts an employee number from the user and gives his or her commission:

  1. Imports Oracle.DataAccess.Client
  2.  
  3. Public Class Form12
  4.  
  5. Private Sub btnGetCommission_Click(ByVal sender As
  6. System.Object, ByVal e As System.EventArgs) Handles
  7. btnGetCommission.Click
  8. 'create connection to db
  9. Dim cn As New OracleConnection("Data Source=xe; _
  10. User Id=scott;Password=tiger")
  11. Try
  12. 'create the command object
  13. Dim cmd As New OracleCommand("SELECT comm FROM _
  14. emp WHERE empno=" & Me.txtEmpno.Text, cn)
  15. 'open the connection from command
  16. cmd.Connection.Open()
  17. 'execute the command and get the single value
  18. 'result
  19. Dim result As Double = cmd.ExecuteScalar
  20. cmd.Connection.Close()
  21. cmd.Dispose()
  22. 'display the output
  23. MessageBox.Show("Commission: " & result)
  24. Catch ex As Exception
  25. 'display if any error occurs
  26. MessageBox.Show("Error: " & ex.Message)
  27. 'close the connection if it is still open
  28. If cn.State = ConnectionState.Open Then
  29. cn.Close()
  30. End If
  31. End Try
  32. End Sub
 

In the highlighted statement above, we are expecting a numeric (or double) value as the result. If the ExecuteScalar returns a double value, it would never be a problem. What if it returns a NULL? The following is the error you would receive:

To deal with the above error, we may have to include our own condition to test against nulls in the output. Just replace the highlighted code above with the following two statements and it should work fine now:

Dim result As Object = cmd.ExecuteScalar
If IsDBNull(result) Then result = 0

You can observe from the above two lines that we are receiving the value in the form of an object and assigning a value zero if it is null.


Trackback(0)
Comments (0)add comment

Write comment

busy
 
< Prev   Next >
Exforsys Offers
© 2008 Exforsys.com
Joomla! is Free Software released under the GNU/GPL License.
Page copy protected against web site content infringement by Copyscape