Using SQLDataReader instead of recordset

前端 未结 3 1844
无人及你
无人及你 2020-12-30 09:33

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 dbCon         


        
相关标签:
3条回答
  • 2020-12-30 09:49
    Dim rdrDataReader As SqlClient.SqlDataReader
    Dim cmdCommand As SqlClient.SqlCommand
    Dim dtsData As New DataSet
    Dim dtbTable As New DataTable
    Dim i As Integer
    Dim SQLStatement as String
    
    msqlConnection.Open()
    
    cmdCommand = New SqlClient.SqlCommand(SQLStatement, msqlConnection)
    
    rdrDataReader = cmdCommand.ExecuteReader()
    
    For i = 0 To (rdrDataReader.FieldCount - 1)
        dtbTable.Columns.Add(rdrDataReader.GetName(i), rdrDataReader.GetFieldType(i))
    Next
    dtbTable.BeginLoadData()
    
    Dim values(rdrDataReader.FieldCount - 1) As Object
    
    While rdrDataReader.Read
        rdrDataReader.GetValues(values)
        dtbTable.LoadDataRow(values, True)
    End While
    dtbTable.EndLoadData()
    
    dtsData.Tables.Add(dtbTable)
    
    msqlConnection.Close()
    
    Return dtsData
    
    0 讨论(0)
  • 2020-12-30 10:02

    You will have to swap out a few things, something similar to the following.

    Here is an example, you will need to modify this to meet your goal, but this shows the difference.

    I also recommend using a "Using" statement to manage the connection/reader. Also, a parameterized query.

    Dim sConnection As String = "server=(local);uid=sa;pwd=PassWord;database=DatabaseName"
    
    Dim objCommand As New SqlCommand
    objCommand.CommandText = "Select * From tablename"
    objCommand.Connection = New SqlConnection(sConnection)
    objCommand.Connection.Open()
    
    Dim objDataReader As SqlDataReader = objCommand.ExecuteReader()
    
    If objDataReader.HasRows Then
    Do While objDataReader.Read()
    Console.WriteLine(" Your name is: " & Convert.ToString(objDataReader(0)))
    Loop
    Else
    Console.WriteLine("No rows returned.")
    End If
    
    objDataReader.Close()
    objCommand.Dispose()
    
    0 讨论(0)
  • 2020-12-30 10:07

    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
    
    0 讨论(0)
提交回复
热议问题