天天看點

利用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與thisAdapter關聯,這樣就不用自己寫sql的更新語句了

            SqlCommandBuilder thisBuilder = new SqlCommandBuilder(thisAdapter);

            //注::  DataSet、DataTable、DataRow、DataColumn是表中的資料在記憶體中的表示。為了更新資料庫,需要調用Update()方法

            DataSet thisDataSet = new DataSet();

            thisAdapter.Fill(thisDataSet, "Customers");

            Console.WriteLine("Name before change:{0}", thisDataSet.Tables["Customers"].Rows[9]["CompanyName"]);

            thisDataSet.Tables["Customers"].Rows[9]["CompanyName"] = "Acme, Inc.";

            thisAdapter.Update(thisDataSet, "Customers");

            Console.WriteLine("name after change:{0}", thisDataSet.Tables["Customers"].Rows[9]["CompanyName"]);

            thisConnection.Close();

            Console.Write("Program finished, press Enter/Return to continue:");

            Console.ReadLine();

        }

    }