您的位置:首页 > 数据库

SqlDataAdapter用法

2011-03-19 11:28 351 查看
在ADO.NET的DataAdapter其实是由很多个Command组成的。
如SelectCommand,DeleteCommand,InsertCommand,UpdateCommand。
每一个Command都是一个独立的Command对象。也就是都有自己的Connection和CommandText。
DataAdapter的所有工作都会落实到一个Command上,比如查询就用SelectCommand。如果SelectCommand没有配置好,就不能执行这个工作。
相应的,如果要执行Update方法,就必须配置好UpdateCommand。而我们通常的定义中(如:OleDbDataAdapter da=new OleDbDataAdapter("Select * From Authors",conn);)都只是配置了SelectCommand,所以这时DataAdapter只能执行查询工作,而不能执行Update。
要让DataAdapter执行Update,当然就必须配置好UpdateCommand。但是这个Command的CommandText相当复杂(如果有N个字段的话,就有2*N+1个参数),如果要我们手工去配置,那简直就是不可能的。所以.NET为我们提供那一个自动配置其Command的工具CommandBuilder。用这个Class,我们就能把DataAdapter的所有Command配置好,从而使它能执行这些操作。
CommandBuilder也有两种:OleDbCommandBuilder和SqlCommandBuilder。分别对应OleDb和SQL Server。
public static void CreateSqlDataAdapter()
{
SqlDataAdapter custDA = new SqlDataAdapter("SELECT CustomerID, CompanyName FROM Customers",
"Data Source=localhost;Integrated Security=SSPI;Initial Catalog=northwind");
SqlConnection custConn = custDA.SelectCommand.Connection;

custDA.MissingSchemaAction = MissingSchemaAction.AddWithKey;

custDA.InsertCommand = new SqlCommand("INSERT INTO Customers (CustomerID, CompanyName) " +
"VALUES (@CustomerID, @CompanyName)", custConn);
custDA.UpdateCommand = new SqlCommand("UPDATE Customers SET CustomerID = @CustomerID, CompanyName = @CompanyName " +
"WHERE CustomerID = @oldCustomerID", custConn);
custDA.DeleteCommand = new SqlCommand("DELETE FROM Customers WHERE CustomerID = @CustomerID", custConn);

custDA.InsertCommand.Parameters.Add("@CustomerID", SqlDbType.Char, 5, "CustomerID");
custDA.InsertCommand.Parameters.Add("@CompanyName", SqlDbType.VarChar, 40, "CompanyName");

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

custDA.DeleteCommand.Parameters.Add("@CustomerID", SqlDbType.Char, 5, "CustomerID").SourceVersion = DataRowVersion.Original;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: