alt
Advertisement
Sponsored links
Online Training
Career Series
Exforsys
Exforsys arrow Tutorials arrow ODP.NET arrow ODP.NET - Filling a DataTable Using OracleDataReader
Site Search


ODP.NET - Filling a DataTable Using OracleDataReader

ODP.NET - Filling a DataTable Using OracleDataReader

So far, we have been filling data tables using OracleDataAdapter. ADO.NET 2.0 gives us the flexibility to fill a data table using OracleDataReader as well. The following code gives you the details of all employees available in the emp table by filling a data table using an OracleDataReader:

  1. Dim cn As New OracleConnection("Data Source=xe; _
  2. User Id=scott;Password=tiger")
  3. Try
  4. Dim SQL As String
  5. Dim dt As New DataTable
  6. 'build the SELECT statement
  7. SQL = String.Format("SELECT empno, ename, job,
  8. mgr, hiredate, sal, comm, deptno FROM emp")
  9. 'create command object to work with SELECT
  10. Dim cmd As New OracleCommand(SQL, cn)
  11. 'open the connection
  12. cmd.Connection.Open()
  13. 'get the DataReader object from command object
  14. Dim rdr As OracleDataReader = _
  15. cmd.ExecuteReader(CommandBehavior.CloseConnection)
  16. 'check if it has any rows
  17. If rdr.HasRows Then
  18. 'simply bind datatable to grid
  19. dt.Load(rdr, LoadOption.OverwriteChanges)
  20. Me.DataGridView1.DataSource = dt
  21. Else
  22. 'display message if no rows found
  23. MessageBox.Show("Not found")
  24. Me.DataGridView1.Rows.Clear()
  25. End If
  26. rdr.Close()
  27. Catch ex As Exception
  28. 'display if any error occurs
  29. MessageBox.Show("Error: " & ex.Message)
  30. 'close the connection if it is still open
  31. If cn.State = ConnectionState.Open Then
  32. cn.Close()
  33. End If
  34. End Try
 

Once the OracleConnection and OracleDataReader are created, we need to create and fill a DataTable object using OracleDataReader itself. The following is the statement that creates a DataTable object:

Dim dt As New DataTable

To fill the above DataTable object with respect to OracleDataReader, we can directly use the Load method of DataTable, which accepts a DataReader object and the type of LoadOption. The following statement loads the content of an OracleDataReader into a DataTable object with a LoadOption as OverwriteChanges (overwrites all the modifications that are available as part of the DataTable object):

dt.Load(rdr, LoadOption.OverwriteChanges)


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