漫漫技术人生路

C#

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

RowState
http://hi.baidu.com/my666666/blog/item/0f95ba8b7a43c3dafd1f10b2.html
The SqlDataAdapter object serves as a bridge between an ADO.NET DataSet object and a SQL Server database. SqlDataAdapter is an intermediary object that populates an ADO.NET DataSet object with data that is retrieved from a SQL Server database, then updates the database to reflect the changes (such as inserts, updates, and deletes) that are made to the data by using the DataSet object.

   TabbleMappings集合

        默认情况下,SqlDataAdapter假定SqlDataReader中的列与DataSet中的列匹配,但实际情况中往往期望DataSet的架构不同于数据库的架构,因此SqlDataAdapter提供了一种将查询结果映射到DataSet结果的机制:TableMappings集合。

        SqlDataAdapter的TableMappings属性返回一个DataTableMappingsConnention对象,它包含DataTableMapping对象的集合。每个对象允许在数据库中的一个表(或视图或存储过程)与DataSet中相对应的DataTable的名称之间建立一种映射;TableMappings对象具有ColumnMappings属性,它返回DataColumnMappings对象组成的集合,每个DataColumnMappings对象对应数据库查询结果中的一列映射到DataSet中DataTable中的一列
DataTableMapping tableMap;
tableMap=da.TableMappings.Add(“Table”,”Employees”);

SqlDataAdapter的构造函数

strSql是查询数符串;strConn是数据库连接字符串;cmd是SqlCommand对象;cn是SqlConnection对象。         SqlDataAdapter da=new SqlDataAdapter(strSql,strConn);
SqlDataAdapter da=new SqlDataAdapter(strSql,cn);
SqlDataAdapter da=new SqlDataAdapter(cmd);
 执行以上代码后,DataSet的实例对象ds中会创建一个新的DataTable,这个DataTable拥有strSql查询语句中所包括的字段,但DataTable对象的名称为默认的Table,而不是查询语句中所查询的表的名称。da.Fill(DataSet,”MyTableName”)// SqlDataAdapter填充指定DataSet的特定表。
da.Fill(DataTable);// SqlDataAdapter填充已经创建的DataTable对象。
da.Fill(DataSet,intStartRecord,intNumRecord,”TableName”);//Fill方法可能很轻松的实现分页显示,但操作效率很低

TableMappings映射
TabbleMappings集合控制SqlDataAdapter如何将DataSet映射到数据库。如果保持TabbleMappings集合为空,调用Fill方法,然后将DataSet作为参数,而不指定表名,SqlDataAdapter将假定您希望使用一个名为“Table”的DataTable来装载数据。
SqlDataAdapter.TableMappings.Add(“Table”,”Employees”)
此语句的作用是将DataSet中原来名字为“Table”的DataTable命名为“Employees”,DataSet填充数据时,按查询结果集的顺序依次填充DataSet中的Table、Table1、Table2……,所以给DataTable命名时需留意该DataTable是否为当前将要使用的对象。

AddRange:
DataColumnMapping[] columnMaps;

        columnMaps=new DataColumnMapping[];

        {new DataColumnMapping (“EmpID”,”EmployeeID”),

        new DataColumnMapping (“LName”,”LastName”)

        }

        tableMap.ColumnMapping.AddRange(columnMaps);
 MissingMappingAction属性

        当SqlDataAdapter提取查询结果来填充DataSet时,它将检查TableMappings集合,如果存在结果集中列不在TableMappings集合时,它将查看MissingMappingAction属性的值来决定如何操作。

        Passthrough 映射中没有出现的列仍然填充到DataSet,采用原结果集的名称;

        Ignore 忽略映射中没有出现的列;

        Error 在出现不匹配的情况下引发异常;

//更新数据(UpDate方法自动遍历DataTable中的行,以找出需要对数据库作出变动)
 //Rows集合中每个DataRow对象都具有属性RowState,可以跟踪此行是否已删除、添加、修改,还是未作变动。所作的任何变化都会反映到数据库中。
sdaAdapter.Update(dsSet, "customers");

 

SqlDataReader
只能顺序读,不能修改数据库
在程序没执行完之前一直保持连接
SqlDataAdapter
一次读出,可以放在DataSet里的。可以用来修改数据库.
SqlDataReader.RecordsAffected 属性
获取执行 Transact-SQL 语句所更改、插入或删除的行数。
如果没有任何行受到影响或语句失败,则为 0;-1 表示 SELECT 语句。
直到读取了所有行并关闭 SqlDataReader 时,才会设置 RecordsAffected 属性。
该属性的值是累积值。例如,如果以批处理模式插入两个记录,则 RecordsAffected 的值将为二。
当 SqlDataReader 关闭后,只能调用 IsClosed 和 RecordsAffected 属性。
SqlDataReader.VisibleFieldCount 属性
获取 SqlDataReader 中未隐藏的字段的数目。

SqlDataReader.NextResult 方法
当读取批处理 Transact-SQL 语句的结果时,使数据读取器前进到下一个结果。
返回值
如果存在多个结果集,则为 true;否则为 false。

SqlDataReader.FieldCount 属性
获取当前行中的列数。

 using (DataTable table = new DataTable { TableName = "OrderSummary" })
protected void Page_Load(object sender, EventArgs e)
{   
IDataReader reader = cust.GetCustomerOrderSummary("99999");  
 using (DataSet ds = new DataSet()) 
  {      
 using (DataTable table = new DataTable { TableName = "OrderSummary" })   
{          
  DataColumn idColumn = table.Columns.Add("number", typeof(int));    
  table.Columns.Add("name", typeof(string));           
  table.Columns.Add("quantity", typeof(int));           
  table.Columns.Add("prev_quantity", typeof(int));           
  table.PrimaryKey = new DataColumn[] { idColumn };           
  while (reader.Read())         
  {            
  table.Rows.Add( new object[]{ reader[0], reader[1], reader[2], reader[3] }  );  
               table.AcceptChanges();   
  }            ds.Tables.Add(table);          
  rptCustomerOrder report = new rptCustomerOrder { DataSource = ds };         
  ReportViewer1.Report = report;      
 }    }}

DataViewRowState Enumeration
OriginalRows Original rows including unchanged and deleted rows.
Current rows including unchanged, new, and modified rows.
ModifiedCurrent A current version of original data that has been modified 
ModifiedOriginal The original version of the data that was modified. (Although the data has since been modified, it is available as ModifiedCurrent).
static private void DemonstrateRowState()
{
    // Create a DataTable with one column.
    DataTable dataTable = new DataTable("dataTable");
    DataColumn dataColumn = new DataColumn("dataColumn");
    dataTable.Columns.Add(dataColumn);

    // Add ten rows.
    DataRow dataRow;
    for (int i = 0; i < 10; i++)
    {
        dataRow = dataTable.NewRow();
        dataRow["dataColumn"] = "item " + i;
        dataTable.Rows.Add(dataRow);
    }
    dataTable.AcceptChanges();

    // Create a DataView with the table.
    DataView dataView = new DataView(dataTable);

    // Change one row's value:
    dataTable.Rows[1]["dataColumn"] = "Hello";
 //dataTable.AcceptChanges(); 如果没有这个 dataTable.AcceptChanges();那么变化是不会反映在dataTable中的,那么下面dataTable.Rows[1].Delete();,删除的是items1 ,如果有了dataTable.AcceptChanges(); ,dataTable.Rows[1].Delete();删除的是"Hello";
    // Add one row:
    dataRow = dataTable.NewRow();
    dataRow["dataColumn"] = "World";
    dataTable.Rows.Add(dataRow);

    // Set the RowStateFilter to display only added and modified rows.
    dataView.RowStateFilter = DataViewRowState.Added
        | DataViewRowState.ModifiedCurrent;

    // Print those rows. Output = "Hello" "World";
    PrintView(dataView, "ModifiedCurrent and Added");

    // Set filter to display on originals of modified rows.
    dataView.RowStateFilter = DataViewRowState.ModifiedOriginal;//old data
//DataViewRowState.ModifiedCurrent new data
//DataViewRowState.CurrentRows still exists
//DataViewRowState.OriginalRows 全部开始时初始化得到的,不包括后来增加的,修改的
    PrintView(dataView, "ModifiedOriginal");

    // Delete three rows.
    dataTable.Rows[1].Delete();
    dataTable.Rows[2].Delete();
    dataTable.Rows[3].Delete();

    // Set the RowStateFilter to display only Added and modified rows.
    dataView.RowStateFilter = DataViewRowState.Deleted;
    PrintView(dataView, "Deleted");

    //Set filter to display only current.
    dataView.RowStateFilter = DataViewRowState.CurrentRows;
    PrintView(dataView, "Current");

    // Set filter to display only unchanged rows.
    dataView.RowStateFilter = DataViewRowState.Unchanged;
    PrintView(dataView, "Unchanged");

    // Set filter to display only original rows.
    dataView.RowStateFilter = DataViewRowState.OriginalRows;
    PrintView(dataView, "OriginalRows");
}


static private void PrintView(DataView dataView, string label)
{
    Console.WriteLine("\n" + label);
    for (int i = 0; i < dataView.Count; i++)
    {
        Console.WriteLine(dataView[i]["dataColumn"]);
    }
}

  DataRowCollection rowCollection = table.Rows;
    // Instantiate a new row using the NewRow method.
    DataRow newRow = table.NewRow();
    // Insert code to fill the row with values.
    // Add the row to the DataRowCollection.
    table.Rows.Add(newRow);

 

SqlDataAdapter 是用来读取SQL语句或命令的。
SqlCommandBuilder是用来执行SQL的

//修改数据源,Update方法首先获取DataTable对象的变化情况,然后逐行地修改
//在ADO.NET 2.0中,可以在Update之前设置UpdateBatchSize的值,以一批修改多条记录的方式
 //发送给数据库,来提高性能
SqlDataAdapter的Update   方法后自动调用DataTable.AcceptChanges方法

DataTable.Select("字段 Like '%模糊值%'")

DataSet dataSet = new DataSet("CustomerOrders");
customerAdapter.Fill(dataSet, "Customers");
orderAdapter.Fill(dataSet, "Orders");
DataRelation customerOrders = dataSet.Relations.Add(
  "CustOrders", dataSet.Tables["Customers"].Columns["CustomerID"],
  dataSet.Tables["Orders"].Columns["CustomerID"]);
请注意,Customers 元素和 Orders 元素显示为同辈元素。 如果您要让 Orders 元素显示为它们各自父元素的子元素,则需要将 DataRelation 的 Nested 属性设置为 true,为此将添加以下代码:
customerOrders.Nested = true;
foreach (DataRow custRow in customerOrders.Tables["Customers"].Rows)
{
    Console.WriteLine("Customer ID: " + custRow["CustomerID"]);

    foreach (DataRow orderRow in custRow.GetChildRows(customerOrdersRelation))
    {
        Console.WriteLine("  Order ID: " + orderRow["OrderID"]);
        Console.WriteLine("\tOrder Date: " + orderRow["OrderDate"]);

        foreach (DataRow detailRow in orderRow.GetChildRows(orderDetailRelation))
        {
            Console.WriteLine("\t Product: " +
                detailRow.GetParentRow(orderProductRelation)["ProductName"]);
            Console.WriteLine("\t Quantity: " + detailRow["Quantity"]);
        }
    }
}
DataRelation(string relationName, DataColumn parentColumn, DataColumn childColumn, bool createConstraints
参数:
relationName:关系名称,此参数如果为空引用(Visual Basic 中为Nothing) 或空字符串(""),则当创建的对象添加到DataRelationCollection 时,将指定一个默认名称。
parentColumn:关系中的父级 DataColumn。
childColumn:关系中的子级 DataColumn。
createConstraints:指示是否要创建约束的值。如果要创建约束,则为true;否则为false。
使用下面代码为子DataList动态指定数据源。
DataSource='<%# ((System.Data.DataRowView)Container.DataItem).CreateChildView("BookPublish") %>'>//BookPublish 为constrains

DataTable..::.Clone Method

Clones the structure of the DataTable, including all DataTable schemas and constraints.

DataTable..::.Copy Method

Copies both the structure and data for this DataTable.
(same as dataset)


DataTable..::.Compute Method

Computes the given expression on the current rows that pass the filter criteria.

private void ComputeBySalesSalesID(DataSet dataSet)
{
    // Presumes a DataTable named "Orders" that has a column named "Total."
    DataTable table;
    table = dataSet.Tables["Orders"];

    // Declare an object variable.
    object sumObject;
    sumObject = table.Compute("Sum(Total)", "EmpID = 5");
}

file copy process is used
if exist "$(TargetPath).locked" del "$(TargetPath).locked"
 if not exist "$(TargetPath).locked" if exist "$(TargetPath)" move "$(TargetPath)" "$(TargetPath).locked"

posted on 2009-08-20 17:53  javaca88  阅读(240)  评论(0编辑  收藏  举报