Read the data with the DataReader object in VB.NET

This article is a brief introduction to read data with the datareader object in ADO.NET using Visual Basic
  • 51649
 

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

Categories

More Articles

© 2020 DotNetHeaven. All rights reserved.