Какой из них использовать: Dataset или Datatable или Datareader - PullRequest
0 голосов
/ 17 августа 2011

Я прочитал статьи о наборе данных, datatable и datareader, но все еще не понимаю, когда что использовать?Может ли кто-нибудь помочь мне с примерами, чтобы понять, какой из них подходит в каком контексте?

1 Ответ

3 голосов
/ 18 августа 2011

DataTable - это объект, используемый для хранения данных столбца и строки для одной таблицы.

    Dim dt As New Data.DataTable
    dt.Columns.Add("ColumnA", GetType(String))
    dt.Columns.Add("ColumnB", GetType(Int32))
    dt.Rows.Add("TestData1", 1)
    dt.Rows.Add("TestData2", 2)

    For Each dr As Data.DataRow In dt.Rows
        Response.Write(String.Format("{0}, {1}", dr.Item(0), dr.Item(0)))
    Next

Datareader - это объект, используемый для чтения одной строки за раз из базы данных.

    Using oConn As New Data.SqlClient.SqlConnection
        Dim oCmd = oConn.CreateCommand
        Dim oRead = oCmd.ExecuteReader
        While oRead.Read
            Response.Write(oRead.Item(0).ToString)
        End While
    End Using

Набор данных - это коллекция DataTables.С помощью набора данных вы также можете хранить отношения и ограничения между родительскими таблицами и дочерними таблицами.Вы можете создать целую реляционную базу данных в памяти с помощью набора данных.Наборы данных могут быть созданы с помощью кода или с помощью редактора наборов данных в Visual Studio.Если вы делаете это с помощью Visual Studio (XSD-файл), набор данных становится «типизированным», поэтому вы можете ссылаться на столбцы в скомпилированном коде по имени, а не по индексу или литералу.

    Dim ds As New dsMain
    Dim drParent = ds.ParentTable.AddParentTableRow("1")
    Dim drChild = ds.ChildTable.AddChildTableRow(drParent, "Somedata")

    Response.Write(drChild.ChildData & drChild.ParentTableRow.ParentId.ToString)

И код для dsMain.XSD ...

<?xml version="1.0" encoding="utf-8"?>
<xs:schema id="dsMain" targetNamespace="http://tempuri.org/dsMain.xsd" xmlns:mstns="http://tempuri.org/dsMain.xsd" xmlns="http://tempuri.org/dsMain.xsd" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" xmlns:msprop="urn:schemas-microsoft-com:xml-msprop" attributeFormDefault="qualified" elementFormDefault="qualified">
  <xs:annotation>
    <xs:appinfo source="urn:schemas-microsoft-com:xml-msdatasource">
      <DataSource DefaultConnectionIndex="0" FunctionsComponentName="QueriesTableAdapter" Modifier="AutoLayout, AnsiClass, Class, Public" SchemaSerializationMode="IncludeSchema" xmlns="urn:schemas-microsoft-com:xml-msdatasource">
        <Connections />
        <Tables />
        <Sources />
      </DataSource>
    </xs:appinfo>
  </xs:annotation>
  <xs:element name="dsMain" msdata:IsDataSet="true" msdata:UseCurrentLocale="true" msprop:Generator_UserDSName="dsMain" msprop:Generator_DataSetName="dsMain">
    <xs:complexType>
      <xs:choice minOccurs="0" maxOccurs="unbounded">
        <xs:element name="ParentTable" msprop:Generator_TableClassName="ParentTableDataTable" msprop:Generator_TableVarName="tableParentTable" msprop:Generator_TablePropName="ParentTable" msprop:Generator_RowDeletingName="ParentTableRowDeleting" msprop:Generator_UserTableName="ParentTable" msprop:Generator_RowChangingName="ParentTableRowChanging" msprop:Generator_RowEvHandlerName="ParentTableRowChangeEventHandler" msprop:Generator_RowDeletedName="ParentTableRowDeleted" msprop:Generator_RowEvArgName="ParentTableRowChangeEvent" msprop:Generator_RowChangedName="ParentTableRowChanged" msprop:Generator_RowClassName="ParentTableRow">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="ParentId" msprop:Generator_ColumnVarNameInTable="columnParentId" msprop:Generator_ColumnPropNameInRow="ParentId" msprop:Generator_ColumnPropNameInTable="ParentIdColumn" msprop:Generator_UserColumnName="ParentId" type="xs:string" />
            </xs:sequence>
          </xs:complexType>
        </xs:element>
        <xs:element name="ChildTable" msprop:Generator_TableClassName="ChildTableDataTable" msprop:Generator_TableVarName="tableChildTable" msprop:Generator_TablePropName="ChildTable" msprop:Generator_RowDeletingName="ChildTableRowDeleting" msprop:Generator_UserTableName="ChildTable" msprop:Generator_RowChangingName="ChildTableRowChanging" msprop:Generator_RowEvHandlerName="ChildTableRowChangeEventHandler" msprop:Generator_RowDeletedName="ChildTableRowDeleted" msprop:Generator_RowEvArgName="ChildTableRowChangeEvent" msprop:Generator_RowChangedName="ChildTableRowChanged" msprop:Generator_RowClassName="ChildTableRow">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="ParentId" msprop:Generator_ColumnVarNameInTable="columnParentId" msprop:Generator_ColumnPropNameInRow="ParentId" msprop:Generator_ColumnPropNameInTable="ParentIdColumn" msprop:Generator_UserColumnName="ParentId" type="xs:string" />
              <xs:element name="ChildData" msprop:Generator_ColumnVarNameInTable="columnChildData" msprop:Generator_ColumnPropNameInRow="ChildData" msprop:Generator_ColumnPropNameInTable="ChildDataColumn" msprop:Generator_UserColumnName="ChildData" type="xs:string" minOccurs="0" />
            </xs:sequence>
          </xs:complexType>
        </xs:element>
      </xs:choice>
    </xs:complexType>
    <xs:unique name="Constraint1" msdata:PrimaryKey="true">
      <xs:selector xpath=".//mstns:ParentTable" />
      <xs:field xpath="mstns:ParentId" />
    </xs:unique>
    <xs:unique name="ChildTable_Constraint1" msdata:ConstraintName="Constraint1" msdata:PrimaryKey="true">
      <xs:selector xpath=".//mstns:ChildTable" />
      <xs:field xpath="mstns:ParentId" />
    </xs:unique>
    <xs:keyref name="FK_ParentTable_ChildTable" refer="Constraint1" msprop:rel_Generator_UserChildTable="ChildTable" msprop:rel_Generator_ChildPropName="GetChildTableRows" msprop:rel_Generator_ParentPropName="ParentTableRow" msprop:rel_Generator_UserRelationName="FK_ParentTable_ChildTable" msprop:rel_Generator_RelationVarName="relationFK_ParentTable_ChildTable" msprop:rel_Generator_UserParentTable="ParentTable">
      <xs:selector xpath=".//mstns:ChildTable" />
      <xs:field xpath="mstns:ParentId" />
    </xs:keyref>
  </xs:element>
</xs:schema>

Надеюсь, это поможет.

...