DeleteCommand属性---删除数据集指定的行保存到数据源中
数据集中删除指定行实例
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using System.Data.SqlClient; namespace PersistDeletes { class Program { static void Main(string[] args) { string connString = @"server=.; integrated security=true; database =northwind"; string qry = @"select * from employees where country='UK'"; string del = @" delete from employees where employeeid =@employeeid"; SqlConnection conn = new SqlConnection(connString); try { SqlDataAdapter da = new SqlDataAdapter(); da.SelectCommand = new SqlCommand(qry, conn); DataSet ds = new DataSet(); da.Fill(ds, "employees"); DataTable dt = ds.Tables["employees"]; SqlCommand cmd = new SqlCommand(del, conn); cmd.Parameters.Add("@employeeid", SqlDbType.Int, 4, "employeeid"); string filt = @"firstname='tan' and lastname = 'ding'"; foreach (DataRow row in dt.Select(filt)) { row.Delete(); } da.DeleteCommand = cmd; da.Update(ds, "employees"); foreach (DataRow row in dt.Rows) { Console.WriteLine("{0} {1} {2}", row["firstname"].ToString().PadRight(15), row["lastname"].ToString().PadLeft(25), row["city"]); } } catch(Exception e) { Console.WriteLine("Error: "+e); }finally { conn.Close(); } Console.ReadKey(); } } }
示例说明
添加一个DELETE语句
string del = @"
delete from employees
where employeeid =@employeeid";
将DELETE代码放在显示代码之前。在创建命令,映射参数后,代码如下所示:
SqlCommand cmd = new SqlCommand(del, conn);
cmd.Parameters.Add("@employeeid", SqlDbType.Int, 4, "employeeid");
选择要删除的行,并删除它。实际上,我们选择了名为tan ding的雇员的所有行,因为不知道这些雇员的ID。尽管我们只想选择一行,仍使用一个循环删除所有的行
string filt = @"firstname='tan' and lastname = 'ding'";
foreach (DataRow row in dt.Select(filt))
{
row.Delete();
}
最后,用命令设置数据适配器的DeleteCommand属性,从Employees表中删除行,该命令是在调用Upate方法时,数据适配器执行的SQL。接着在数据适配器上调用Update()方法,将变化保存在数据库中。
da.DeleteCommand = cmd;
da.Update(ds, "employees");
无论是删除一行还是删除多选,SQL都是参数化的,所以数据适配器会在employees数据表中查找所有已删除的行,并把对它们的所有删除操作都提交给Employees数据库表。