ADO.NET提供了前端控制項和後端資料庫之間的橋樑。NET對象封裝了所有的數據訪問操作,控制項與這些對象交互以顯示數據,從而隱藏了數據移動的細節。
下圖顯示了ADO.NET對象:
The DataSet Class
數據集表示資料庫的一個子集。它沒有到資料庫的連續連接。要更新資料庫,需要重新連接。數據集包含數據表對象和數據關係對象。DataRelation對象表示兩個表之間的關係。
下表顯示了數據集類的一些重要屬性:
Properties | Description |
---|---|
CaseSensitive | Indicates whether string comparisons within the data tables are case-sensitive. |
Container | Gets the container for the component. |
DataSetName | Gets or sets the name of the current data set. |
DefaultViewManager | Returns a view of data in the data set. |
DesignMode | Indicates whether the component is currently in design mode. |
EnforceConstraints | Indicates whether constraint rules are followed when attempting any update operation. |
Events | Gets the list of event handlers that are attached to this component. |
ExtendedProperties | Gets the collection of customized user information associated with the DataSet. |
HasErrors | Indicates if there are any errors. |
IsInitialized | Indicates whether the DataSet is initialized. |
Locale | Gets or sets the locale information used to compare strings within the table. |
Namespace | Gets or sets the namespace of the DataSet. |
Prefix | Gets or sets an XML prefix that aliases the namespace of the DataSet. |
Relations | Returns the collection of DataRelation objects. |
Tables | Returns the collection of DataTable objects. |
下表顯示了數據集類的一些重要方法:
Methods | Description |
---|---|
AcceptChanges | Accepts all changes made since the DataSet was loaded or this method was called. |
BeginInit | Begins the initialization of the DataSet. The initialization occurs at run time. |
Clear | Clears data. |
Clone | Copies the structure of the DataSet, including all DataTable schemas, relations, and constraints. Does not copy any data. |
Copy | Copies both structure and data. |
CreateDataReader() | Returns a DataTableReader with one result set per DataTable, in the same sequence as the tables appear in the Tables collection. |
CreateDataReader(DataTable[]) | Returns a DataTableReader with one result set per DataTable. |
EndInit | Ends the initialization of the data set. |
Equals(Object) | Determines whether the specified Object is equal to the current Object. |
Finalize | Free resources and perform other cleanups. |
GetChanges | Returns a copy of the DataSet with all changes made since it was loaded or the AcceptChanges method was called. |
GetChanges(DataRowState) | Gets a copy of DataSet with all changes made since it was loaded or the AcceptChanges method was called, filtered by DataRowState. |
GetDataSetSchema | Gets a copy of XmlSchemaSet for the DataSet. |
GetObjectData | Populates a serialization information object with the data needed to serialize the DataSet. |
GetType | Gets the type of the current instance. |
GetXML | Returns the XML representation of the data. |
GetXMLSchema | Returns the XSD schema for the XML representation of the data. |
HasChanges() | Gets a value indicating whether the DataSet has changes, including new, deleted, or modified rows. |
HasChanges(DataRowState) | Gets a value indicating whether the DataSet has changes, including new, deleted, or modified rows, filtered by DataRowState. |
IsBinarySerialized | Inspects the format of the serialized representation of the DataSet. |
Load(IDataReader, LoadOption, DataTable[]) | Fills a DataSet with values from a data source using the supplied IDataReader, using an array of DataTable instances to supply the schema and namespace information. |
Load(IDataReader, LoadOption, String[]) | Fills a DataSet with values from a data source using the supplied IDataReader, using an array of strings to supply the names for the tables within the DataSet. |
Merge() | Merges the data with data from another DataSet. This method has different overloaded forms. |
ReadXML() | Reads an XML schema and data into the DataSet. This method has different overloaded forms. |
ReadXMLSchema(0) | Reads an XML schema into the DataSet. This method has different overloaded forms. |
RejectChanges | Rolls back all changes made since the last call to AcceptChanges. |
WriteXML() | Writes an XML schema and data from the DataSet. This method has different overloaded forms. |
WriteXMLSchema() | Writes the structure of the DataSet as an XML schema. This method has different overloaded forms. |
The DataTable Class
DataTable類表示資料庫中的表。它具有以下重要屬性;這些屬性中的大多數是只讀屬性,PrimaryKey屬性除外:
Properties | Description |
---|---|
ChildRelations | Returns the collection of child relationship. |
Columns | Returns the Columns collection. |
Constraints | Returns the Constraints collection. |
DataSet | Returns the parent DataSet. |
DefaultView | Returns a view of the table. |
ParentRelations | Returns the ParentRelations collection. |
PrimaryKey | Gets or sets an array of columns as the primary key for the table. |
Rows | Returns the Rows collection. |
下表顯示了DataTable類的一些重要方法:
Methods | Description |
---|---|
AcceptChanges | Commits all changes since the last AcceptChanges. |
Clear | Clears all data from the table. |
GetChanges | Returns a copy of the DataTable with all changes made since the AcceptChanges method was called. |
GetErrors | Returns an array of rows with errors. |
ImportRows | Copies a new row into the table. |
LoadDataRow | Finds and updates a specific row, or creates a new one, if not found any. |
Merge | Merges the table with another DataTable. |
NewRow | Creates a new DataRow. |
RejectChanges | Rolls back all changes made since the last call to AcceptChanges. |
Reset | Resets the table to its original state. |
Select | Returns an array of DataRow objects. |
The DataRow Class
DataRow對象表示表中的行。它具有以下重要特性:
Properties | Description |
---|---|
HasErrors | Indicates if there are any errors. |
Items | Gets or sets the data stored in a specific column. |
ItemArrays | Gets or sets all the values for the row. |
Table | Returns the parent table. |
下表顯示了DataRow類的一些重要方法:
Methods | Description |
---|---|
AcceptChanges | Accepts all changes made since this method was called. |
BeginEdit | Begins edit operation. |
CancelEdit | Cancels edit operation. |
Delete | Deletes the DataRow. |
EndEdit | Ends the edit operation. |
GetChildRows | Gets the child rows of this row. |
GetParentRow | Gets the parent row. |
GetParentRows | Gets parent rows of DataRow object. |
RejectChanges | Rolls back all changes made since the last call to AcceptChanges. |
The DataAdapter Object
DataAdapter對象充當數據集對象和資料庫之間的中介。這有助於數據集包含來自多個資料庫或其他數據源的數據。
The DataReader Object
DataReader對象是DataSet和DataAdapter組合的替代對象。此對象提供對資料庫中數據記錄的面向連接的訪問。這些對象適合只讀訪問,例如填充列表,然後斷開連接。
DbCommand and DbConnection Objects
DbConnection對象表示到數據源的連接。可以在不同的命令對象之間共享連接。
DbCommand對象表示從檢索或操作數據發送到資料庫的命令或存儲過程。
Example
到目前爲止,我們已經使用了計算機中已經存在的表和資料庫。在本例中,我們將創建一個表,向其中添加列、行和數據,並使用GridView對象顯示該表。
源文件代碼如下所示:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="createdatabase._Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title> Untitled Page </title> </head> <body> <form id="form1" runat="server"> <div> <asp:GridView ID="GridView1" runat="server"> </asp:GridView> </div> </form> </body> </html>
代碼隱藏文件如下所示:
namespace createdatabase { public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { DataSet ds = CreateDataSet(); GridView1.DataSource = ds.Tables["Student"]; GridView1.DataBind(); } } private DataSet CreateDataSet() { //creating a DataSet object for tables DataSet dataset = new DataSet(); // creating the student table DataTable Students = CreateStudentTable(); dataset.Tables.Add(Students); return dataset; } private DataTable CreateStudentTable() { DataTable Students = new DataTable("Student"); // adding columns AddNewColumn(Students, "System.Int32", "StudentID"); AddNewColumn(Students, "System.String", "StudentName"); AddNewColumn(Students, "System.String", "StudentCity"); // adding rows AddNewRow(Students, 1, "M H Kabir", "Kolkata"); AddNewRow(Students, 1, "Shreya Sharma", "Delhi"); AddNewRow(Students, 1, "Rini Mukherjee", "Hyderabad"); AddNewRow(Students, 1, "Sunil Dubey", "Bikaner"); AddNewRow(Students, 1, "Rajat Mishra", "Patna"); return Students; } private void AddNewColumn(DataTable table, string columnType, string columnName) { DataColumn column = table.Columns.Add(columnName, Type.GetType(columnType)); } //adding data into the table private void AddNewRow(DataTable table, int id, string name, string city) { DataRow newrow = table.NewRow(); newrow["StudentID"] = id; newrow["StudentName"] = name; newrow["StudentCity"] = city; table.Rows.Add(newrow); } } }
執行程序時,請注意以下事項:
應用程式首先創建一個數據集,並使用grid view控制項的DataBind()方法將其與GridView控制項綁定。
Createdataset()方法是一個用戶定義的函數,它創建一個新的數據集對象,然後調用另一個用戶定義的方法CreateStudentTable()來創建表並將其添加到數據集的表集合中。
CreateStudentTable()方法調用用戶定義的方法AddNewColumn()和AddNewRow()來創建表的列和行,並向行中添加數據。
執行頁面時,它返回表中的行,如下所示: