用DataSet对数据库进行增 、删、 查

class Program
    {
        static void Main(string[] args)
        {
            SqlConnection thisConnection = new SqlConnection(
                  @"Data Source=.\SQLEXPRESS;" +
                  @"AttachDbFilename='C:\SQL Server 2000 Sample Databases\NORTHWND.MDF';"
                  +
                  @"Integrated Security=true;Connect Timeout=30;User Instance=true");


            SqlDataAdapter thisAdapter = new SqlDataAdapter(
                "select CustomerID, CompanyName FROM Customers", thisConnection);
            SqlCommandBuilder thisBuilder = new SqlCommandBuilder(thisAdapter);


            DataSet thisDataSet = new DataSet();
            thisAdapter.Fill(thisDataSet, "Customers");
            Console.WriteLine("# rows before change:{0}", thisDataSet.Tables["Customers"].Rows.Count);
            // 为DataSet中的Customers设置主键,通过主键可以找到唯一的一行数据(主键应为唯一值)
            //-----------------------------主键设置 begin------------------------------
            DataColumn[] keys = new DataColumn[1];
            keys[0] = thisDataSet.Tables["Customers"].Columns["CustomerID"];
            thisDataSet.Tables["Customers"].PrimaryKey = keys;
            //如果不这样设置主键,就直接从数据库中加载主键,但必须在填充DataSet之前设置DataAdapter对象的MissingSchemaAction
            //thisAdapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;
            //-----------------------------主键设置 end------------------------------
            DataRow findRow = thisDataSet.Tables["Customers"].Rows.Find("ZACZI");//查找行
            if (findRow == null)
            {
                Console.WriteLine("ZACZI not found,will add to Customers table");


                DataRow thisRow = thisDataSet.Tables["Customers"].NewRow();
                thisRow["CustomerID"] = "ZACZI";
                thisRow["CompanyName"] = "Zachary Zithers Ltd.";
                thisDataSet.Tables["Customers"].Rows.Add(thisRow);//添加行
                if ((findRow = thisDataSet.Tables["Customers"].Rows.Find("ZACZI")) != null)
                {
                    Console.WriteLine("ZACZI successfully added to Customerstable");
                }
            }
            else
            {
                Console.WriteLine("ZACZI already present in database");
                Console.WriteLine("Removing ZACZI...");
                findRow.Delete();//删除行
            }


            thisAdapter.Update(thisDataSet, "Customers");
            Console.WriteLine("# rows afterchange:{0}", thisDataSet.Tables["Customers"].Rows.Count);
            thisConnection.Close();
            Console.WriteLine();
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值