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","CustomerID");
  adapter.UpdateCommand.Parameters.Add("@CompanyName","CompanyName");
  adapter.UpdateCommand.Parameters.Add("@oldCustomerID","CustomerID").SourceVersion = DataRowVersion.Original; 
  adapter.DeleteCommand.Parameters.Add("@CustomerID","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)

相关文章

项目中经常遇到CSV文件的读写需求,其中的难点主要是CSV文件...
简介 本文的初衷是希望帮助那些有其它平台视觉算法开发经验的...
这篇文章主要简单记录一下C#项目的dll文件管理方法,以便后期...
在C#中的使用JSON序列化及反序列化时,推荐使用Json.NET——...
事件总线是对发布-订阅模式的一种实现,是一种集中式事件处理...
通用翻译API的HTTPS 地址为https://fanyi-api.baidu.com/api...