DeleteCommand属性---删除数据集指定的行保存到数据源中
數據集中刪除指定行實例
View Code 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 employeeswhere 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數據庫表。
?
?
總結
以上是生活随笔為你收集整理的DeleteCommand属性---删除数据集指定的行保存到数据源中的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mysql 交叉表
- 下一篇: error_logs