用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();
        }
    }

你可能感兴趣的:(用DataSet对数据库进行增 、删、 查)