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)