从数据库中删除数据

// 从数据库中删除数据
// DelCmd.cs
using System;
using System.Data;
using System.Data.SqlClient;
namespace Ch13
{
    class DelCmd
    {
        static void Main( string[] args)
        {
            string strConn = "server=.\\MSSQL2012;integrated security=true;database=Northwind";
            string qry = "select * from employees where employeeid>8" ;
            string del = "delete from employees where employeeid=@empid";
            SqlConnection conn = new SqlConnection(strConn);
            try
            {
                SqlDataAdapter da = new SqlDataAdapter();
                da.SelectCommand = new SqlCommand(qry, conn);
                DataSet ds = new DataSet();
                da.Fill(ds, "emp");
                DataTable dt = ds.Tables[ "emp"];

                Console.WriteLine( "删除前");
                foreach (DataRow row in dt.Rows)
                {
                    Console.WriteLine( "{0} {1} {2} {3}"
                        , row[ "employeeid"].ToString().PadRight(5)
                        , row[ "firstname"].ToString().PadRight(15)
                        , row[ "lastname"].ToString().PadRight(15)
                        , row[ "city"]);

                }

                SqlCommand cmd = new SqlCommand(del, conn);
                cmd.Parameters.Add( "@empid", SqlDbType.Int, 4, "employeeid");
                string filter = "firstname='张' and lastname='三'" ;
                foreach (DataRow row in dt.Select(filter))
                {
                    row.Delete();
                }
                da.DeleteCommand = cmd;
                da.Update(ds, "emp");

                Console.WriteLine( "删除后");
                foreach (DataRow row in dt.Rows)
                {
                    Console.WriteLine( "{0} {1} {2} {3}"
                        , row[ "employeeid"].ToString().PadRight(5)
                        , row[ "firstname"].ToString().PadRight(15)
                        , row[ "lastname"].ToString().PadRight(15)
                        , row[ "city"]);
                }
            }
            catch( Exception ex)
            {
                Console.WriteLine( "出错了:" + ex);
            }
            finally
            {
                conn.Close();
                Console.ReadLine();
            }
        }
    }
}
-------------
删除前
9     Anne            Dodsworth       London
15    张               三               深圳
删除后
9     Anne            Dodsworth       London


来自为知笔记(Wiz)


posted on 2013-08-24 00:29  伊利丹  阅读(409)  评论(0编辑  收藏  举报