Exforsys

Home arrow Reviews arrow ODP.NET

ODP.NET - OracleCommand Object

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

ODP.NET - More About the OracleCommand Object

Till now, we have seen OracleCommand working with OracleDataReader. OracleCommand is not simply meant for OracleDataReader. It has got a lot of functionality for itself. Let us see few of the most commonly used features of OracleCommand in this section. We will further go into depth in subsequent sections and chapters.

Ads

Retrieving a Single Value from the Database

As we already covered working with single or multiple rows, we need to work on retrieving a single value from database very effectively. We have already retrieved row values in our previous examples, but those examples are more suitable when you are trying to deal with entire rows.

OracleCommand is equipped with a method called ExecuteScalar, which is mainly used to retrieve single values from the database very efficiently thus improving the performance. The following example focuses on this:

Sample Code
  1. Imports Oracle.DataAccess.Client
  2.  
  3. Public Class Form9
  4.   Private Sub btnEmployeeCount_Click(ByVal sender As 
  5.   System.ObjectByVal e As System.EventArgs) Handles 
  6.   btnEmployeeCount.Click
  7.     'create connection to db
  8.     Dim cn As New OracleConnection("Data Source=xe; _
  9.                          User Id=scott;Password=tiger")
  10.     Try
  11.       'create the command object
  12.       Dim cmd As New OracleCommand("SELECT COUNT(*) _
  13.                                         FROM emp", cn)
  14.       'open the connection from command
  15.       cmd.Connection.Open()
  16.       'execute the command and get the single value 
  17.       'result
  18.       Dim result As String = cmd.ExecuteScalar
  19.       'clear the resources
  20.       cmd.Connection.Close()
  21.       cmd.Dispose()
  22.       'display the output
  23.  
  24.       MessageBox.Show("No. of Employees: " & result)
  25.     Catch ex As Exception
  26.       'display if any error occurs
  27.       MessageBox.Show("Error: " & ex.Message)
  28.       'close the connection if it is still open
  29.       If cn.State = ConnectionState.Open Then
  30.         cn.Close()
  31.       End If
  32.     End Try
  33.   End Sub
  34. End Class
Copyright exforsys.com


Ads

The highlighted line in the above code simply executes the SELECT command, which retrieves the number of rows from the emp table and assigns this value to the result variable.



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

ODP.NET

 

Comments