ARTICLE

How to read the data with the DataReader object in ADO.NET

Posted by Rohatash Kumar Articles | ADO.NET in VB.NET February 09, 2011
This article is a brief introduction to read data with the datareader object in ADO.NET using Visual Basic.
Download Files:
 
Reader Level:

Data Reader

There are two way two way to read the data which is stored in database. One way is DataSet and other is DataReader. Dataset works with disconnected mode and DataReader works with connected architecture. DataReader is used only for read only and forward only so we can not do any transaction on them. using DataReader we can able to access one row at a time so there is no need to storing it in memory.

Creating a SqlDataReader Object

To create a SqldataReader we must call ExecuteReader on a command object.

Dim myreader As SqlDataReader = cmd.ExecuteReader()

 

Now creating a table in Database and insert the value. like this

 

create table emp

(

firstname varchar(20),

lastname varchar(30)

)

 

Now using select statement.

 

select * from emp;


1.gif 

Table1.gif

 

OUTPUT

 

Reading the table data with DataReader

 

The below example will get the employee firstname and last name from the table emp from MS SQL server database.

 

Imports System.Data.SqlClient

Module Module1

    Sub Main()

        Dim str As String = "Data Source=.;uid=sa; pwd=123;database=master"

        Dim con As New SqlConnection(str)

        Try

            con.Open()

            Dim sql As String = "SELECT * FROM emp;"

            Dim cmd As New SqlCommand(sql, con)

            Dim myreader As SqlDataReader = cmd.ExecuteReader()

            Console.WriteLine("Firstname & lastname ")

            Console.WriteLine("=============================")

            While myreader.Read()

                Console.Write(myreader("Firstname").ToString() & ", ")

                Console.Write(myreader("Lastname").ToString() & ", ")

                Console.WriteLine("")

            End While

        Catch ex As SqlException

            Console.WriteLine("Error: " & ex.ToString())

        End Try

    End Sub

End Module

 

OUTPUT


2.gif

Login to add your contents and source code to this article
share this article :
post comment
 
Nevron Diagram
Become a Sponsor
PREMIUM SPONSORS
  • ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications. Visit DynamicPDF here
    The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Nevron Diagram
Become a Sponsor