首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# DataSet 與 DataTable 詳解 (7) — 欄位/主鍵/外鍵/資料列操作

     編輯:關於C語言

新增欄位與約束


DataColumn col = dt.Columns.Add("newColumn", typeof(int));
col.AllowDBNull = false; col.MaxLength = 4; col.Unique = true;
dt.PrimaryKey = new DataColumn[] { dt.Columns["ID"] };
// 複合主鍵
dt.PrimaryKey = new DataColumn[] { dt.Columns["OrderID"], dt.Columns["ProductID"] };

外鍵約束


ForeignKeyConstraint fk = new ForeignKeyConstraint(
    ds.Tables["Customers"].Columns["CustomerID"],
    ds.Tables["Orders"].Columns["CustomerID"]);
ds.Tables["Orders"].Constraints.Add(fk);

修改 DataRow


DataRow dr = ds.Tables["Customer"].Rows.Find("ANTON");
if (dr != null) {
    dr.BeginEdit();
    dr["CompanyName"] = "newValue";
    dr["ContactName"] = "newValue2";
    dr.EndEdit();
}
  • BeginEdit/EndEdit 緩衝修改,CancelEdit 可取消
  • Find 需主鍵已設定

判斷 Null 與指派 DBNull


DataRow dr = ds.Tables["Customers"].Rows.Find("aaa");
if (dr.IsNull("ContactName")) { /* ... */ }
else dr["ContactName"] = DBNull.Value;
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved