How to update a database from a DataSet object

How to update a database from a DataSet object

This section demonstrates how to use the DataSet object to update data in a database. It is important to remember that you can also use a SqlCommand object to insert, update, and delete data in a database directly.

After the DataSet is loaded, you can modify the data. The DataSet will track these changes. The DataSet object can be considered an in-memory cache of data that is retrieved from a database. The DataSet object consists of a collection of tables, relationships, and constraints.

To update a DataSet and send those updates back to the database, follow these steps:

1.       Start Visual Studio 2005 or Visual Studio .NET.

2.       Create a new Console Application in Visual C#. Visual Studio creates a Static Class by default and an empty Main() procedure.

3.       Make sure that the project contains a reference to the System and System.Data namespaces. Use the using statement on the System, System.Data, and System.Data.SqlClient namespaces so that you are not required to qualify declarations from these namespaces later in your code. You must use these statements prior to any other declarations.

4.           using System;
5.           using System.Data;
6.           using System.Data.SqlClient;
                                

7.       Before you can modify the data and submit the changes back to the database, you must load the information into the DataSet.
The connection string in the following code points to a SQL Server that is located on the local computer (or the computer where the code is running)To summarize, a connection is created, and then a data adapter is created, which is used to fill the DataSet with data.
Note You must change User ID <username> and password<strong password> to the correct values before you run this code. Make sure that User ID has the appropriate permissions to perform this operation on the database.

8.           string sConnectionString;
9.            
10.       // Modify the following string to correctly connect to your SQL Server.
11.       sConnectionString = "Password=<strong password>;User ID=<username>;"
12.               + "Initial Catalog=pubs;"
13.               + "Data Source=(local)";
14.        
15.       SqlConnection objConn
16.               = new SqlConnection(sConnectionString);
17.       objConn.Open();
18.        
19.       // Create an instance of a DataAdapter.
20.       SqlDataAdapter daAuthors 
21.               = new SqlDataAdapter("Select * From Authors", objConn);
22.        
23.       // Create an instance of a DataSet, and retrieve data from the Authors table.
24.       DataSet dsPubs = new DataSet("Pubs");
25.       daAuthors.FillSchema(dsPubs,SchemaType.Source, "Authors");
26.       daAuthors.Fill(dsPubs,"Authors");
                                

27.   Now that the data is loaded, you can modify it. There are many ways to add a row (or record). This code sample uses a three step procedure:

o        Obtain a new DataRow object from the DataTable.

o        Set the DataRow field values as necessary.

o        Pass that new object into the Add method of the DataTable.Rows collection.

Paste the following code after the code in step 4:

 //****************
// BEGIN ADD CODE 
// Create a new instance of a DataTable.
 DataTable tblAuthors;
tblAuthors = dsPubs.Tables["Authors"];
 
DataRow drCurrent;
// Obtain a new DataRow object from the DataTable.
 drCurrent = tblAuthors.NewRow();
 
// Set the DataRow field values as necessary.
 drCurrent["au_id"] = "993-21-3427";
drCurrent["au_fname"] = "George";
drCurrent["au_lname"] = "Johnson";
 drCurrent["phone"] = "800 226-0752";
drCurrent["address"] = "1956 Arlington Pl.";
drCurrent["city"] = "Winnipeg";
 drCurrent["state"] = "MB";
drCurrent["contract"] = 1;
 
// Pass that new object into the Add method of the DataTable.
tblAuthors.Rows.Add(drCurrent);
 Console.WriteLine("Add was successful, Click any key to continue!!");
 Console.ReadLine();
 
// END ADD CODE  
                                 

28.   To edit existing rows, obtain the appropriate DataRow object, and then provide new values for one or more columns. You must first find the correct row, which is much easier because you loaded the schema of the table as well as the data (the call to FillSchema in step 4). With the schema in place, the table knows which column is its primary key, and the Find method of the Rows collection is available.

The Find method returns the DataRow object with a specific value in its primary key (in this case, au_id). After you have that DataRow, you can modify the columns. You do not have to wrap the modifications in BeginEdit and EndEdit, but this simplifies the work that the DataSet has to do and allows the DataSet to perform its validation checks simultaneously when EndEdit is called. Paste the following code after the ADD code:

29.       //*****************
30.       // BEGIN EDIT CODE 
31.        
32.       drCurrent = tblAuthors.Rows.Find("213-46-8915");
33.       drCurrent.BeginEdit();
34.       drCurrent["phone"] = "342" + drCurrent["phone"].ToString().Substring(3);
35.       drCurrent.EndEdit();
36.       Console.WriteLine("Record edited successfully, Click any key to continue!!");
37.       Console.ReadLine();
38.        
39.       // END EDIT CODE  
                                

40.   To update the original database with all of these changes, pass the DataSet into the Update method of the DataAdapter object.

However, before you can call Update, you must set the InsertCommand, UpdateCommand, and DeleteCommand properties of the DataAdapter object. You can manually write SQL and populate these three properties with corresponding SqlCommand objects, but you can also use Visual Studio .NET to generate these three commands automatically.

To generate the required commands when they are needed, you must create an instance of the SqlCommandBuilder object and use the DataAdapter in the constructor. If you want to use this method, which is illustrated in the code sample to follow, you must have primary key information available for your table. To access primary key information, call FillSchema, and then set the MissingSchemaAction property of your DataAdapter to AddWithKey, or manually set the primary key in your code. Paste the following code after the EDIT code:

41.       //*****************
42.       // BEGIN SEND CHANGES TO SQL SERVER 
43.        
44.       SqlCommandBuilder objCommandBuilder = new SqlCommandBuilder(daAuthors);
45.       daAuthors.Update(dsPubs, "Authors");
46.       Console.WriteLine("SQL Server updated successfully, Check Server explorer to see changes");
47.       Console.ReadLine();
48.        
49.       // END SEND CHANGES TO SQL SERVER
                                

50.   To delete a row completely, use the Delete method of the DataRow object. Note that the Rows collection contains two methods, Remove and RemoveAt, which seem to delete the row but instead just remove the row from the collection. Only the Delete method sends your deletion back to the source database. Paste the following code after the SEND CHANGES TO SQL SERVER code:

51.       //*****************
52.       //BEGIN DELETE CODE 
53.        
54.       drCurrent = tblAuthors.Rows.Find("993-21-3427");
55.       drCurrent.Delete();
56.       Console.WriteLine("Record deleted successfully, Click any key to continue!!"); 
57.       Console.ReadLine();
58.        
59.       //END DELETE CODE 
                                

60.   Send the changes to SQL Server to remove the record that you added earlier. Paste the following code after the DELETE code:

61.       //*****************
62.       // CLEAN UP SQL SERVER
63.       daAuthors.Update(dsPubs, "Authors");
64.       Console.WriteLine("SQL Server updated successfully, Check Server explorer to see changes");
65.       Console.ReadLine();
                                

66.   Save your project.

67.   On the Debug menu, click Start to run the project. Notice that several message boxes appear, which indicate the progress of the code and allow you to review the current state of the data as the code progresses.

 

Complete code listing

 using System;
using System.Data;
using System.Data.SqlClient;
 
namespace PopulateDataSet
{
 
    /// <summary>
    /// Summary description for Class1.
     /// </summary>
    class Class1
    {
        static void Main(string[] args)
        {
            string sConnectionString;
 
            // Modify the following string to correctly connect to your SQL Server.
            sConnectionString = "Password=;User ID=sa;"
                 + "Initial Catalog=pubs;"
                + "Data Source=(local)";
 
            SqlConnection objConn
                = new SqlConnection(sConnectionString);
             objConn.Open();
 
            // Create an instance of a DataAdapter.
             SqlDataAdapter daAuthors 
                = new SqlDataAdapter("Select * From Authors", objConn);
 
            // Create an instance of a DataSet, and retrieve 
            // data from the Authors table.
             DataSet dsPubs = new DataSet("Pubs");
            daAuthors.FillSchema(dsPubs,SchemaType.Source, "Authors");
            daAuthors.Fill(dsPubs,"Authors"); 
             //****************
            // BEGIN ADD CODE 
            // Create a new instance of a DataTable.
             DataTable tblAuthors;
            tblAuthors = dsPubs.Tables["Authors"];
 
            DataRow drCurrent;
            // Obtain a new DataRow object from the DataTable.
             drCurrent = tblAuthors.NewRow();
 
            // Set the DataRow field values as necessary.
             drCurrent["au_id"] = "993-21-3427";
            drCurrent["au_fname"] = "George";
            drCurrent["au_lname"] = "Johnson";
             drCurrent["phone"] = "800 226-0752";
            drCurrent["address"] = "1956 Arlington Pl.";
            drCurrent["city"] = "Winnipeg";
             drCurrent["state"] = "MB";
            drCurrent["contract"] = 1;
 
            // Pass that new object into the Add method of the DataTable.
            tblAuthors.Rows.Add(drCurrent);
             Console.WriteLine("Add was successful, Click any key to continue!!");
             Console.ReadLine();
 
            // END ADD CODE   
             //*****************
            // BEGIN EDIT CODE 
 
            drCurrent = tblAuthors.Rows.Find("213-46-8915");
            drCurrent.BeginEdit();
             drCurrent["phone"] = "342" + drCurrent["phone"].ToString().Substring(3);
             drCurrent.EndEdit();
            Console.WriteLine("Record edited successfully, Click any key to continue!!");
            Console.ReadLine();
                       
            // END EDIT CODE   
             //*****************
            // BEGIN SEND CHANGES TO SQL SERVER 
 
            SqlCommandBuilder objCommandBuilder = new SqlCommandBuilder(daAuthors);
            daAuthors.Update(dsPubs, "Authors");
             Console.WriteLine("SQL Server updated successfully, Check Server explorer to see changes");
             Console.ReadLine();
                       
            // END SEND CHANGES TO SQL SERVER 
             //*****************
            //BEGIN DELETE CODE 
 
            drCurrent = tblAuthors.Rows.Find("993-21-3427");
            drCurrent.Delete();
            Console.WriteLine("SRecord deleted successfully, Click any key to continue!!"); 
            Console.ReadLine();
       
            //END DELETE CODE  
             //*****************
            // CLEAN UP SQL SERVER
            daAuthors.Update(dsPubs, "Authors");
             Console.WriteLine("SQL Server updated successfully, Check Server explorer to see changes");
             Console.ReadLine();               
                       
        }
    }
}
                               

 

 

 


Share

Twitter Delicious Facebook Digg Stumbleupon Favorites