C# SqlDataAdapter

SqlDataAdapter 比DataAdapter更进一步,专门用来操作SQL Server 数据库。

一、 方法

  SqlDataAdapter有两个有用的方法,分别为 fill 和 update。下面分别来介绍这两方法。

1. fill 方法

  fill 方法是用来填充 DataSet 的。也就是,把数据库中的运送到C#空间。fill 有13个重载的方法,在使用时可以根据情况选择使用。使用 FillSchema,让 SqlDataAdapter 创建DataSet 的架构,并在用数据填充它之前就将主键信息包括进去。

2. update 方法

  update 方法是用来更改数据库的。也就是,把C#内存中修改的内容同步到数据库中。更新是逐行进行的。对于插入、修改和删除,Update 方法会自动确定类型(Insert、Update 或 Delete)。

二、属性

  SqlDataAdapter有5个有用的属性,分别为SelectCommand、InsertCommand、DeleteCommand、UpdateCommand 和TableMappings 属性。其中,TableMappings 表示列的映射关系。其他的属性通过名字就能知道它所做的操作了。

示例一:

private static DataSet SelectRows(DataSet dataset, string connectionString,string queryString) 
{
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        SqlDataAdapter adapter = new SqlDataAdapter();
        adapter.SelectCommand = new SqlCommand(queryString, connection);
        adapter.Fill(dataset);
        return dataset;
    }
}

 示例二:

创建 SqlDataAdapter 并将 MissingSchemaAction 设置为 AddWithKey,以便从数据库中检索其他架构信息。SelectCommand、InsertCommand、UpdateCommand 和 DeleteCommand 属性集及其相应的SqlParameter 对象已添加到 Parameters 集合。该方法返回一个 SqlDataAdapter 对象。

public static SqlDataAdapter CreateSqlDataAdapter(SqlConnection connection)

{
  SqlDataAdapter adapter = new SqlDataAdapter();
  adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;

  // Create the commands.
  adapter.SelectCommand = new SqlCommand("SELECT CustomerID, CompanyName FROM CUSTOMERS", connection);
  adapter.InsertCommand = new SqlCommand("INSERT INTO Customers (CustomerID, CompanyName) " + "VALUES (@CustomerID, @CompanyName)",  connection);
  adapter.UpdateCommand = new SqlCommand("UPDATE Customers SET CustomerID = @CustomerID, CompanyName = @CompanyName " + "WHERE   CustomerID = @oldCustomerID", connection);
  adapter.DeleteCommand = new SqlCommand("DELETE FROM Customers WHERE CustomerID = @CustomerID", connection);

  // Create the parameters.
  adapter.InsertCommand.Parameters.Add("@CustomerID", SqlDbType.Char, 5, "CustomerID");
  adapter.InsertCommand.Parameters.Add("@CompanyName", SqlDbType.VarChar, 40, "CompanyName");

  adapter.UpdateCommand.Parameters.Add("@CustomerID", SqlDbType.Char, 5, "CustomerID");
  adapter.UpdateCommand.Parameters.Add("@CompanyName",SqlDbType.VarChar, 40, "CompanyName");
  adapter.UpdateCommand.Parameters.Add("@oldCustomerID", SqlDbType.Char, 5, "CustomerID").SourceVersion = DataRowVersion.Original;
  adapter.DeleteCommand.Parameters.Add("@CustomerID", SqlDbType.Char, 5, "CustomerID").SourceVersion = DataRowVersion.Original;
  return adapter;
}

参考文献 http://msdn.microsoft.com/zh-cn/library/system.data.sqlclient.sqldataadapter.fill(v=vs.90)

    http://msdn.microsoft.com/zh-cn/library/879f39d8(v=vs.90)

原文地址:https://www.cnblogs.com/fengkuangshubiaodian/p/2611367.html