Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using SQLDataReader instead of recordset

I am new to this and had this question. Can I use SQLDataReader instead of a Recordset. I want to achieve the following result in an SQLDataReader.

Dim dbConn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim sqlstr As String = "SELECT Name,Status FROM table1 WHERE id=" + item_id.Value.ToString
rs.Open(SQL, dbConn)
While Not rs.EOF
   txtName.Text = rs.Fields.Item("Name").Value
   ddlstatus.SelectedIndex = 1
   rs.MoveNext()
End While
rs.Close()
rs = Nothing
dbConn.Close()
dbConn = Nothing

Can I replace recordset with SQLDataReader and if I can can you please show me the changes in code?

like image 658
nerts Avatar asked Jan 28 '10 19:01

nerts


People also ask

Why do we use SqlDataReader?

It is used to populate an array of objects with the column values of the current row. It is used to get the next result, when reading the results of SQL statements. It is used to read record from the SQL Server database. To create a SqlDataReader instance, we must call the ExecuteReader method of the SqlCommand object.

What is difference between SqlDataReader and SqlDataAdapter?

A SqlDataAdapter is typically used to fill a DataSet or DataTable and so you will have access to the data after your connection has been closed (disconnected access). The SqlDataReader is a fast forward-only and connected cursor which tends to be generally quicker than filling a DataSet/DataTable.

Does SqlDataReader close connection?

The SqlConnection is closed automatically at the end of the using code block.

Is there anything faster than SqlDataReader in net?

SqlDataReader is the fastest way. Make sure you use the get by ordinal methods rather than get by column name. e.g. GetString(1);


1 Answers

Its highly recommend that you use the using pattern:

    Dim sConnection As String = "server=(local);uid=sa;pwd=PassWord;database=DatabaseName"
    Using Con As New SqlConnection(sConnection)
        Con.Open()
        Using Com As New SqlCommand("Select * From tablename", Con)
            Using RDR = Com.ExecuteReader()
                If RDR.HasRows Then
                    Do While RDR.Read
                        txtName.Text = RDR.Item("Name").ToString()
                    Loop
                End If
            End Using
        End Using
        Con.Close()
    End Using
like image 141
Chris Haas Avatar answered Oct 23 '22 08:10

Chris Haas