SqlDataAdapter类主要在MSSQL与DataSet之间执行数据传输工具,本节将介绍如何使用SqlDataAdapter类来填充DataSet和MSSQL执行新增、修改。、删除等操作。
功能说明
SqlDataAdapter类构建在SqlCommand类之上,并提供了许多配合DataSet使用的功能。使用Fill方法可以把从MSSQL得到的查询结果填充到DataSet中。当DataSet中的数据发生了改变时,使用Update方法可以把更改后的数据更新到MSSQL。
语法定义
下面演示如何创建一个SqlDataAdapter类的实例:
//无参数
SqlDataAdapter adapter = new SqlDataAdapter();
//指定CommandText对象构建一个SqlDataAdapter实例
SqlDataAdapter adapter = new SqlDataAdapter("select * from Products");
//指定CommandText和SqlConnection对象构建一个SqlDataAdapter实例
SqlConnection connection = new SqlConnection();
SqlDataAdapter adapter = new SqlDataAdapter("select * from Products",connection);
方法详解
SqlDataAdapter类提供了很多重要的方法
Fill方法和Update方法最为常用,也拥有多个重载。
Fill方法的使用:
static void Main(string[] args) { string connectionString = "Data Source=ip;Initial Catalog=Northwind;Persist Security Info=True;User ID=sa; Password=sa"; SqlDataAdapter adapter = new SqlDataAdapter("select * from Products",connectionString); DataSet ds = new DataSet(); adapter.Fill(ds,"Products"); //填充DataSet并指定表名为"Products" foreach (DataRow dr in ds.Tables["Products"].Rows) { Console.WriteLine(dr["ProductName"].ToString()); } }
注意:使用SqlDataAdapter类时,无须手工调用SqlConnection对象的Open方法。SqlDataAdapter类会自动打开连接,执行完后会自动恢复SqlConnection对象的连接状态。
UpDtae方法的使用:
static void Main(string[] args) { string connectionString = "Data Source=ip;Initial Catalog=Northwind;Persist Security Info=True;User ID=sa; Password=sa"; SqlDataAdapter adapter = new SqlDataAdapter("select * from Products",connectionString); DataSet ds = new DataSet(); adapter.Fill(ds,"Products"); //填充DataSet并指定表名为"Products" ds.Tables["Products"].Rows[0].Delete(); //删除一行数据 SqlCommand deleteCommand = new SqlCommand(); //...此处省略了deleteCommand的属性设置 adapter.DeleteCommand = deleteCommand; if (adapter.Update(ds) > 0) //调用Update方法更新数据 { Console.WriteLine("更新成功"); } }