본문 바로가기

Programming

데이터리더를 데이터셋으로 변환

데이터베이스 조회시 사용하는 Reader 를 데이터셋으로 변환하는 함수입니다

 

Public Function DRtoDS(ByVal reader As SqlClient.SqlDataReader) As DataSet
        Dim dataSet As DataSet = New DataSet
        Dim dataRow As DataRow
        Dim columnName As String
        Dim column As DataColumn
        Dim schemaTable As DataTable
        Dim dataTable As DataTable

        Do
            ' Create new data table
            schemaTable = reader.GetSchemaTable
            dataTable = New DataTable
            If Not IsDBNull(schemaTable) Then
                ' A query returning records was executed
                Dim i As Integer
                For i = 0 To schemaTable.Rows.Count - 1
                    dataRow = schemaTable.Rows(i)
                    ' Create a column name that is unique in the data table
                    columnName = dataRow("ColumnName")
                    'Add the column definition to the data table
                    column = New DataColumn(columnName, CType(dataRow("DataType"), Type))
                    dataTable.Columns.Add(column)
                Next
                dataSet.Tables.Add(dataTable)

                'Fill the data table we just created
                While reader.Read()
                    dataRow = dataTable.NewRow()
                    For i = 0 To reader.FieldCount - 1
                        dataRow(i) = reader(i)
                    Next
                    dataTable.Rows.Add(dataRow)
                End While
            Else
                'No records were returned
                column = New DataColumn("RowsAffected")
                dataTable.Columns.Add(column)
                dataSet.Tables.Add(dataTable)
                dataRow = dataTable.NewRow()
                dataRow(0) = reader.RecordsAffected
                dataTable.Rows.Add(dataRow)
            End If
        Loop While reader.NextResult()
        Return dataSet
    End Function