ADO.NET讀書筆記系列之------DataSet對象

來源:互聯網
上載者:User
ado|筆記|對象
一、特點介紹

1、處理離線資料,在多層應用程式中很有用。

2、可以在任何時候查看DataSet中任意行的內容,允許修改查詢結果的方法。

3、處理分級資料

4、緩衝更改

5、XML的完整性:DataSet對象和XML文檔幾乎是可互換的。

二、使用介紹

1、建立DataSet對象:DataSet ds = new DataSet("DataSetName");

2、查看調用SqlDataAdapter.Fill建立的結構

    da.Fill(ds,"Orders");

    DataTable tbl = ds.Table[0];

    foreach(DataColumn col in tbl.Columns)

        Console.WriteLine(col.ColumnName);

3、查看SqlDataAdapter返回的資料

①、DataRow對象

    DataTable tbl = ds.Table[0];

    DataRow row = tbl.Row[0];

    Console.WriteLine(ros["OrderID"]);

②、檢查儲存在DataRow中的資料

    DataTable tbl = row.Table;

    foreach(DataColumn col in tbl.Columns)

        Console.WriteLine(row[col]);

③、檢查DatTable中的DataRow對象

            foreach(DataRow row in tbl.Rows)

                DisplayRow(row);

4、校正DataSet中的資料

①、校正DataColumn的屬性:ReadOnly,AllowDBNull,MaxLength,Unique

②、DataTable對象的Constrains集合:UiqueConstraints,Primarykey,ForeignkeyConstraints

通常不必刻意去建立ForeignkeyConstraints,因為當在DataSet的兩個DataTable對象之間建立關係時會建立一個。

③、用SqlDataAdapter.Fill模式來檢索模式資訊

5、編寫代碼建立DataTable對象

①、建立DataTable對象:DataTable tbl = new DataTable("TableName");

②、將DataTable添加到DataSet對象的Table集合

    DataSet ds = new DataSet();

    DataTable tbl = new DataTable("Customers");

    ds.Tables.Add(tbl);

 

    DataSet ds = new DataSet();

    DataTable tbl = ds.Tables.Add("Customers");

 DataTable對象只能存在於至多一個DataSet對象中。如果希望將DataTable添加到多個DataSet中,就必須使用Copy方法或Clone方法。Copy方法建立一個與原DataTable結構相同並且包含相同行的新DataTable;Clone方法建立一個與原DataTable結構相同,但沒有包含任何行的新DataTable。

③、為DataTable添加列

    DataTable tbl = ds.Tables.Add("Orders");

    DataColumn col =tbl.Columns.Add("OrderID",typeof(int));

    col.AllowDBNull = false;

    col.MaxLength = 5;

    col.Unique = true;

    tbl.PrimaryKey = new DataColumn[]{tbl.Columns["CustomersID"]};

    當設定主鍵時,AllowDBNull自動化佈建為False;

④、處理自動增量列

    DataSet ds = new DataSet();

    DataTable tbl = ds.Tables.Add("Orders");

    DataColumn col = tbl.Columns.Add("OrderID",typeof(int));

    col.AutoIncrement = true;

    col.AutoIncrementSeed = -1;

    col.AutoIncrementStep = -1;

    col.ReadOnly = true;

⑤、添加基於運算式的列

    tbl.Columns.Add("ItemTotal",typeof(Decimal),"Quantity*UnitPrice");

6、修改DataTable內容

①、添加新DataRow

    DataRow row = ds.Tables["Customers"].NewRow();

    row["CustomerID"] = "ALFKI";

    ds.Tables["Customers"].Rows.Add(row);

 

    object[] aValues ={"ALFKI","Alfreds","Anders","030-22222"};

    da.Tables["Customers"].LoadDataRow(aValues,false);

②、修改當前行

    修改行的內容逼供內不會自動修改資料庫中相應的內容,對行所做的修改被視為是隨後將使用SqlDataAdapter對象來提交交給資料庫的待定的更改。

    DataRow rowCustomer;

    rowCustomer = ds.Tables["Custoemrs"].Rows.Find("ANTON");

    if(rowCustomer == null)

        //沒有尋找客戶

    else

    {

        rowCustomer["CompanyName"] ="NewCompanyName";       

        rowCustomer["ContactName"] ="NewContactName";

    }

 

    //推薦使用這種方式

    DataRow rowCustomer;

    rowCustomer = ds.Tables["Custoemrs"].Rows.Find("ANTON");

    if(rowCustomer == null)

        //沒有尋找客戶

    else

    {

        rowCustomer.BeginEdit();

        rowCustomer["CompanyName"] ="NewCompanyName";       

        rowCustomer["ContactName"] ="NewContactName";

        rowCustomer.EndEdit();

    }

 

    //null表示不修改該列的資料

    obejct[] aCustomer ={null,"NewCompanyName","NewContactName",null}

    DataRow rowCustomer;

    rowCustomer = ds.Tables["Customers"].Rows.Find("ALFKI");

    rowCustomer.ItemArray = aCustomer;

③、處理DataRow的空值

    //查看是否為空白

    DataRow rowCustomer;

    rowCustomer = ds.Tables["Customers"].Rows.Find("ALFKI");

    if(rowCustomer.IsNull("Phone"))

        Console.WriteLine("It's Null");

    else

        Console.WriteLine("It's not Null");

 

    //賦予空值

    rowCustomer["Phone"] = DBNull.Value;

④、刪除DataRow

    DataRow rowCustomer;

    rowCustomer = ds.Tables["Customers"].Rows.Find("ALFKI");

    rowCustomer.Delete();

⑤、清除DataRow

    DataRow rowCustomer = ds.Tables["Customers"].Rows.Find("ALFKI");

    rowCustomer.ItemArray = aCustomer;

    da.Tables["Customers"].Remove(rowCustomer);

    或者

    ds.Tables["Customers"].RemoveAt(intIndex);

⑥、使用DataRow.RowState屬性 :Unchanged,Detached,Added,Modified,Deleted

private void DemonstrateRowState()

{
// Run a function to create a DataTable with one column.
DataTable myTable = MakeTable();
DataRow myRow;

// Create a new DataRow.
myRow = myTable.NewRow();
// Detached row.
Console.WriteLine("New Row " + myRow.RowState);

myTable.Rows.Add(myRow);
// New row.
Console.WriteLine("AddRow " + myRow.RowState);

myTable.AcceptChanges();
// Unchanged row.
Console.WriteLine("AcceptChanges " + myRow.RowState);

myRow["FirstName"] = "Scott";
// Modified row.
Console.WriteLine("Modified " + myRow.RowState);

myRow.Delete();
// Deleted row.
Console.WriteLine("Deleted " + myRow.RowState);
}

⑦、檢查DataRow中的掛起更改

    DataRow rowCustomer;

    rowCustomer = ds.Tables["Customers"].Rows.Find("ALFKI");

    rowCustomer["CompanyName"] = "NewCompanyName";

    string strNewCompanyName,strOldCompanyName;

    Console.WriteLine(rowCustomer["CompanyName",DataRowVersion.Current]);   

    Console.WriteLine(rowCustomer["CompanyName",DataRowVersion.Original]);

三、屬性方法事件介紹

1、DataSet

①、屬性

    CaseSensitive:用於控制DataTable中的字串比較是否區分大小寫。

    DataSetName:當前DataSet的名稱。如果不指定,則該屬性值設定為"NewDataSet"。如果將DataSet內容寫入XML檔案,DataSetName是XML檔案的根節點名稱。

    DesignMode:如果在設計時使用組件中的DataSet,DesignMode返回True,否則返回False。

    HasErrors:表示DataSet中的DataRow對象是否包含錯誤。如果將一批更改提交給資料庫並將DataAdapter對象的ContinueUpdateOnError屬性設定為True,則在提交更改後必須檢查DataSet的HasErrors屬性,以確定是否有更新失敗。

    NameSpace和Prefix:指定XML命名空間和首碼

    Relations:返回一個DataRelationCollection對象。

    Tables:檢查現有的DataTable對象。通過索引訪問DataTable有更好的效能。

②、方法

    AcceptChanges和RejectChanges:接受或放棄DataSet中所有掛起更改。調用AcceptChanges時,RowState屬性值為Added或Modified的所有行的RowState屬性都將被設定為UnChanged.任何標記為Deleted的DataRow對象將從DataSet中刪除。調用RejectChanges時,任何標記為Added的DataRow對象將會被從DataSet中刪除,其他修改過的DatRow對象將返回前一狀態。

    Clear:清除DataSet中所有DataRow對象。該方法比釋放一個DataSet然後再建立一個相同結構的新DataSet要快。

    Clone和Copy:使用Copy方法會建立與原DataSet具有相同結構和相同行的新DataSet。使用Clone方法會建立具有相同結構的新DataSet,但不包含任何行。

    GetChanges:返回與原DataSet對象具有相同結構的新DataSet,並且還包含原DataSet中所有掛起更改的行。

    GetXml和GetXmlSchema:使用GetXml方法得到由DataSet的內容與她的架構資訊轉換為XML格式後的字串。如果只希望返回架構資訊,可以使用GetXmlSchema。

    HasChange:表示DataSet中是否包含掛起更改的DataRow對象。

    Merge:從另一個DataSet、DataTable或現有DataSet中的一組DataRow對象載入資料。

    ReadXml和WriteXml:使用ReadXml方法從檔案、TextReader、資料流或者XmlReader中將XML資料載入DataSet中。

    Reset:將DataSet返回為未初始化狀態。如果想放棄現有DataSet並且開始處理新的DataSet,使用Reset方法比建立一個DataSet的新執行個體好。

③、事件

    MergeFailed:在DataSet的Merge方法發生一個異常時觸發。

2、DataTable

①、屬性

②、方法

③、事件

    ColumnChanged:在列的內容被改變之後觸發

    ColumnChangding:在列的內容被改變之前觸發

    RowChanged,RowChanging,RowDeleted,RowDeleting。

3、DataColumn

①、屬性

4、DataRow

①、屬性

    HasError:確定行是否包含錯誤。

    Item:通過指定行的列數,列的名稱或DataColumn對象本身,訪問列的內容。

    ItemArray:擷取或設定行中所有列的值。

    RowError:返回一個包含行錯誤資訊的字串。

    RowState:返回DataRowState枚舉中的值來表示行的目前狀態。

    Table:返回DataRow對象所在的DataTable。

②、方法

    AcceptChanges和RejectChanges:提交和放棄掛起更改。

    BeginEdit、CancelEdit、EndEdit

    ClearErrors:清除DataRow中所有的錯誤。

    Delete:Delete方法實際上並不從DataRow表的Row集合中刪除該DataRow。當調用DataRow對象的Delete方法時,ADO.NET將該行標記為刪除,之後調用SqlDataAdapter對象的Update方法來刪除其在資料庫中對應的行。

    如果希望徹底刪除DataRow,可以調用Delete方法,接著再調用它的AccepteChanges方法,還可以使用DataRowCollection對象的Remove方法完成相同的任務。

 


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.