c# SQL Server数据库操作-数据适配器类:SqlDataAdapter
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("更新成功"); } }
- 源码: C#操作SQL数据库 SQLDataReader/SQLDataAdapter/DataSet/DataTable
- C#中DataSet、SqlDataAdapter的使用-关于数据库操作
- C# SqlDataAdapter
- 数据读取器对象SqlDataReader与数据适配器对象SqlDataAdapter的使用
- C#数据库编程中SqlDataAdapter与DataSet的区别与联系
- C#里sqlDataAdapter.fill(DataSet,String)的用法
- 如何在 Visual C# .NET 中使用 SqlDataAdapter 对象更新 SQL Server 数据库
- C#里sqlDataAdapter.fill(DataSet,String)的用法
- c#大圣之路笔记——c# SqlDataReader和SqlDataAdapter区别
- C#中ExecuteReader、ExecuteNonQuery、ExecuteScalar、SqlDataReader、SqlDataAdapter应该怎么用?
- 数据读取器对象SqlDataReader与数据适配器对象SqlDataAdapter的使用
- C#中关于SqlDataAdapter的Update(dataTable)方法
- 数据读取器对象SqlDataReader与数据适配器对象SqlDataAdapter的使用
- 1.SqlDataAdapter操作sql2012
- c#之SqlDataAdapter和SqlDataReader
- C#中ExecuteReader、ExecuteNonQuery、ExecuteScalar、SqlDataReader、SqlDataAdapter应该怎么用
- <转载>C#使用SqlDataAdapter.Update更新数据库
- C#利用SqlDataAdapte对DataTable进行批量数据操作
- C# SqlCommand和SqlDataAdapter的区别
- C# SqlDataAdapter和SqlDataReader的区别