Exforsys

Home arrow Reviews arrow ODP.NET

Using keyword in Visual Basic 2005

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

ODP.NET - Retrieving Data Using OracleDataReader

Using 'Using' for Simplicity

The above program can be made simple by using the Using statement together with ODP.NET classes as follows:

Ads

Sample Code
  1. Using cn As New OracleConnection("Data Source=xe;
  2.                       User Id=scott;Password=tiger")
  3.   Try
  4.     cn.Open()
  5.     Dim SQL As String
  6.     SQL = String.Format("SELECT ename, sal, 
  7.      job FROM emp WHERE empno={0}"Me.txtEmpno.Text)
  8.     Using cmd As New OracleCommand(SQL, cn)
  9.     Using rdr As OracleDataReader = cmd.ExecuteReader
  10.         If rdr.HasRows Then
  11.           'read the first row
  12.           rdr.Read()
  13.           'extract the details
  14.           Me.txtEname.Text = rdr("ename")
  15.           Me.txtSal.Text = rdr("sal")
  16.           Me.txtJob.Text = rdr("job")
  17.         Else
  18.           'display message if no rows found
  19.           MessageBox.Show("Not found")
  20.         End If
  21.       End Using
  22.     End Using
  23.   Catch ex As Exception
  24.     MessageBox.Show("Error: " & ex.Message)
  25.     If cn.State = ConnectionState.Open Then
  26.       cn.Close()
  27.     End If
  28.   End Try
  29. End Using
Copyright exforsys.com


The Using keyword is new in Visual Basic 2005, which internally generates try and finally blocks around the object being allocated and calls Dispose() for you saving you the hassle of manually creating it.

Ads

The objects created using the Using keyword are automatically erased (and respective resources would be automatically cleared) from the memory once it is out of using scope. Even though it is very flexible to use the Using statement, for the sake of clarity, we will go without using it in the examples of this book.



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

ODP.NET

 

Comments