DataSet & amp; DataTable & amp; DataRow,

Source: Internet
Author: User
Tags dot net

DataSet & DataTable & DataRow in simple terms,

 

 

This article is suitable for people with a certain degree of foundation to view, it is best to learn a certain degree of net programming basics to view this article.

1. Concept

  DataSetIs the central concept of ADO. NET. DataSet can be regarded as a database in memory, and DataSet is an independent data set independent of the database. The so-called independence means that, even if the data link is disconnected or the database is closed, DataSet is still available, and DataSet uses XML internally to describe the data, because XML is a data description language that is platform-independent and language-independent, and can describe data with complex relationships, such as parent-child relationship data, therefore, DataSet can actually accommodate data with complex relationships and is no longer dependent on database links. We can regard DataSet as a memory database, and DataSet can store multiple tables (DataTable ).DataSet object.

   DataTableIs a virtual grid table that temporarily saves data (a table that represents data in the memory .). DataTable is the core object in the ADO dot net Library. It can be applied to VB and ASP. It can simply bind a database without code. It has a Microsoft-style user interface. Other DataTable objects include DataSet and DataView. DataTable stores the data of a row. The data of this row is the Array of DataRow. Data Table object. DataRowIs the data row in the DataTable, which contains multiple data columns, each column can store different types of values. 2. Common usage of DataSet

DataSet in C # exists in the System. Data namespace, similar to the path in java. DataSet has two columns. The Code is as follows

using System;
using System.Data;

namespace testData
{
    class Program
    {
        static void Main (string [] args)
        {
            DataSet ds1 = new DataSet (); // No construction instance, do not specify DataSetName
            Console.WriteLine (ds1.DataSetName);
            DataSet ds2 = new DataSet ("MySet"); // A construction example, specify DataSetName
            Console.WriteLine (ds2.DataSetName);
            Console.ReadKey ();
        }
    }
}
There are only one common property of DataSet, Tables, which is not explained here. The following are the common properties of DataSet and Tables:

// ds.Tables.Count; // Get the number of tables existing in the data set
// ds.Tables.Add (new DataTable ()); // Add a table (DataTable) to the data set

// DataTable [] array = {new DataTable (), new DataTable (), new DataTable ()};
//ds.Tables.AddRange(array);//Add an array of Table (DataTable) to the data set

//ds.Tables.Remove();//Delete a table
//ds.Tables.RemoveAt();//Delete a table from the data set according to the index of the table
//ds.WriteXml()//Write the xml file to the DataSet dataset
//ds.ReadXml()//Read an xml file into the data set
//ds.Tables.CanRemove()//Verify whether the objects in a collection can be deleted.

 3. Common use of DataTable
 DataTable and DataSet namespace are the same, there are three ways to instantiate, but there are two commonly used, the third specifies the table space; here is not much to explain, now let's look at the two common instance methods

Instantiate 1 DataTable dt0 = new DataTable (); // No table name is specified, the default table name is NewDataTable
Instantiate 2 DataTable dt1 = new DataTable ("User"); // Specify the table name

using System;
using System.Data;

namespace testData
{
    class Program
    {
        static void Main (string [] args)
        {
            DataSet ds = new DataSet ("Set");
            DataTable dt = new DataTable ("User");
            ds.Tables.Add (dt); // Add a table to the data set
            Console.WriteLine (ds.Tables.Count);
            Console.WriteLine (ds.Tables [0] .TableName);
            Console.Read ();
        }
    }
}
Through the above code, we can see that we use the Add method of the DataSet to add a DataTable to the data set.

In the previous overview, we said that DataTable is a data table, the data table must have a table header, so if you create a table header, the code

 DataSet ds = new DataSet ("Set");
            DataTable dt = new DataTable ("User");
            dt.Columns.Add (new DataColumn ("ID", typeof (int))); // Set the table header ID
            dt.Columns.Add ("Name", typeof (string)); // Set the table header Name
            dt.Columns.Add ("Age", Type.GetType ("System.Int32")); // Set the header Name
            for (int i = 0; i <dt.Columns.Count; i ++)
            {
                Console.WriteLine ("Traversing table header mode 1 _____" + dt.Columns [i]);
                
            }
            foreach (var item in dt.Columns)
            {
                Console.WriteLine ("Traverse table header mode 2 ~~~" + item);
            }
            ds.Tables.Add (dt); // Add a table to the data set
            Console.WriteLine ("There are" "+ ds.Tables.Count +" "tables" in the current data set));
            Console.WriteLine ("Table name of the current data set" + ds.Tables [0] .TableName);
            Console.Read ();
 We have such an empty table. Below is how we can add a data row. Do n’t worry, let ’s look at the use of DataRow. We will break down in the advanced section about creating a data row.

 4. Common usage of DataRow
There is only one way to create DataRow, because we set DataRow in the net to not be instantiated, and can only be created by DataTable.NewRow (), such as DataRow dr = dt.NewRow (); Row object.

4.1 How to add row data to DataTable? ? Look at the following code

using System;
using System.Data;

namespace testData
{
    class Program
    {
        static void Main (string [] args)
        {
            DataSet ds = new DataSet ("Set");
            DataTable dt = new DataTable ("User");
            dt.Columns.Add (new DataColumn ("ID", typeof (int))); // Set the table header ID
            dt.Columns.Add ("Name", typeof (string)); // Set the table header Name
            dt.Columns.Add ("Age", Type.GetType ("System.Int32")); // Set the header Name
            for (int i = 0; i <dt.Columns.Count; i ++)
            {
                Console.WriteLine ("Traversing table header mode 1 _____" + dt.Columns [i]);
                
            }
            foreach (var item in dt.Columns)
            {
                Console.WriteLine ("Traverse table header mode 2 ~~~" + item);
            }
            DataRow dr = dt.NewRow ();
            dr ["ID"] = 1;
            dr ["Name"] = "xiaomeng";
            dr ["age"] = 21;
            dt.Rows.Add (dr);
            ds.Tables.Add (dt); // Add a table to the data set
            for (int i = 0; i <dt.Rows.Count; i ++)
            {
                DataRow item = dt.Rows [i];
                Console.WriteLine (item ["name"] + "this year" + item ["age"] + "year old");
            }
            Console.WriteLine ("There are" "+ ds.Tables.Count +" "tables" in the current data set));
            Console.WriteLine ("Table name of the current data set" + ds.Tables [0] .TableName);
            Console.Read ();
        }
    }
}
Many of us programmers think that this will add a data row to the DataTable when they are developing, but this is not the case? See the advanced part for details

 

5. Comprehensive application of CRUD (addition, deletion and modification)
5.1 New

We have an attribute in DataRow called RowState called row state, the row state mainly has the following values: "UnChange" (no change), "Added" (added data), "Modified" (modified data) "Deleted" Delete the data, for example, add the line data above, breakpoint debugging.

Through appeal analysis, we will find that the added data is not submitted to the memory, but only temporarily stored by the program. So how do we submit it, see the following code.

using System;
using System.Data;

namespace testData
{
    class Program
    {
        static void Main (string [] args)
        {
            DataSet ds = new DataSet ("Set");
            DataTable dt = new DataTable ("User");
            dt.Columns.Add (new DataColumn ("ID", typeof (int))); // Set the table header ID
            dt.Columns.Add ("Name", typeof (string)); // Set the table header Name
            dt.Columns.Add ("Age", Type.GetType ("System.Int32")); // Set the header Name
            for (int i = 0; i <dt.Columns.Count; i ++)
            {
                Console.WriteLine ("Traversing table header mode 1 _____" + dt.Columns [i]);
                
            }
            foreach (var item in dt.Columns)
            {
                Console.WriteLine ("Traverse table header mode 2 ~~~" + item);
            }
            DataRow dr = dt.NewRow ();
            dr ["ID"] = 1;
            dr ["Name"] = "xiaomeng";
            dr ["age"] = 21;
            dt.Rows.Add (dr);
            dt.AcceptChanges (); // Submit data
            ds.Tables.Add (dt); // Add a table to the data set
            for (int i = 0; i <dt.Rows.Count; i ++)
            {
                DataRow item = dt.Rows [i];
                Console.WriteLine (item ["name"] + "this year" + item ["age"] + "year old");
            }
            Console.WriteLine ("There are" "+ ds.Tables.Count +" "tables" in the current data set));
            Console.WriteLine ("Table name of the current data set" + ds.Tables [0] .TableName);
            Console.Read ();
        }
    }
}


 

 Submit the code DataTable.AcceptChanges (); Then, if there is a memory commit, should there also be a memory rollback, but it is not introduced here, let's take a look

When the DataTable adds new rows of data, the status is Added. At this time, you can use the DataTable's .AcceptChanges () method to submit, and you can use the RejectChanges () function to roll back.

When the DataTable modifies row data, the status is Modified. At this time, you can use the DataTable's .AcceptChanges () method to submit, and you can use the RejectChanges () function to roll back.

When the DataTable deletes row data, the status is Deleted. At this time, you can use the DataTable's .AcceptChanges () method to submit, and you can use the RejectChanges () function to roll back.

Let's look at the code for addition, deletion and modification

using System;
using System.Data;

namespace testData
{
    class Program
    {
        static void Main (string [] args)
        {
            DataTable dt = new DataTable ();
            DataColumn [] arrayColumn = {
                new DataColumn ("id", typeof (int)),
                new DataColumn ("name", typeof (string)),
                new DataColumn ("age", typeof (int)),
                new DataColumn ("sex", typeof (string))
            };
            dt.Columns.AddRange (arrayColumn);
            Console.WriteLine ("--------------------------- Newly added ---------------- ----------- ");
            DataRow dr0 = null;
            for (int i = 0; i <5; i ++)
            {
                dr0 = dt.NewRow ();
                dr0 [0] = i;
                dr0 [1] = "xiaoming" + i;
                dr0 [2] = 20 + i + new Random (). Next (1,10);
                dr0 [3] = new Random (). Next (i, 200)% 3 == 0? "Male": "Female";
               
                dt.Rows.Add (dr0);
            }
            Console.WriteLine ("Add no new print");
            Print (dt);
            Console.WriteLine ("State ==================" + dr0.RowState);
            dt.AcceptChanges (); // New submission
            Console.WriteLine ("Print after adding new submission");
            Print (dt);
            Console.WriteLine ("State ==================" + dr0.RowState);
            Console.WriteLine ("--------------------------- modify ----------------- ---------- ");
            DataRow dr1 = dt.Rows [0];
            dr1 ["name"] = "wbcsky";
            Console.WriteLine ("Modify not submitted for printing");
            Print (dt);
            Console.WriteLine ("State ==================" + dr1.RowState);
            dt.AcceptChanges (); // New submission
            Console.WriteLine ("Print after modification and submission");
            Print (dt);
            Console.WriteLine ("State ==================" + dr1.RowState);
            Console.WriteLine ("--------------------------- Delete ----------------- ---------- ");
            DataRow dr2 = dt.Rows [0]; // Delete the first
            dr2.Delete (); // Dt.rmove and dt.rmoveat are not used here, because these two methods are directly submitted
            Console.WriteLine ("Delete not submitted for printing");
            Print (dt);
            Console.WriteLine ("State ==================" + dr2.RowState);
            dt.AcceptChanges (); // New submission
            Console.WriteLine ("Delete and print after submission");
            Print (dt);
            Console.WriteLine ("State ==================" + dr2.RowState);
            Console.Read ();
        }

        private static void Print (DataTable dt)
        {
            foreach (DataRow item in dt.Rows)
            {
                string msg = "";
                try
                {
                    msg = $ "id = {item [0]}, name = {item [1]}, age = {item [2]}, sex = {item [3]}";
                }
                catch (Exception e)
                {
                     msg = e.Message;
                   
                }
              
                Console.WriteLine (msg);
            }
        }
    }
}
The execution result is as follows

6. Comprehensive application screening
If we want to sort the above table, how do we sort it? ? ? ? ? , In fact, we can use the DataTable.Select method to sort, let's see how to use

We will see that the select method has four overloads. We only use one parameter and one parameter, one of which is the competition selection, the first of the two parameters is the filter, and the second is the sort.

using System;
using System.Data;

namespace testData
{
    class Program
    {
        static void Main (string [] args)
        {
            DataTable dt = new DataTable ();
            DataColumn [] arrayColumn = {
                new DataColumn ("id", typeof (int)),
                new DataColumn ("name", typeof (string)),
                new DataColumn ("age", typeof (int)),
                new DataColumn ("sex", typeof (string))
            };
            dt.Columns.AddRange (arrayColumn);
           
            DataRow dr0 = null;
            for (int i = 0; i <5; i ++)
            {
                dr0 = dt.NewRow ();
                dr0 [0] = i;
                dr0 [1] = "xiaoming" + i;
                dr0 [2] = 20 + i + new Random (). Next (1,5);
                dr0 [3] = new Random (). Next (i, 200)% 3 == 0? "Male": "Female";
               
                dt.Rows.Add (dr0);
            }
            Console.WriteLine ("--------------------------- before filtering ---------------- ----------- ");
            Print (dtbool session_start (void); Initialize session
bool session_destroy (void): Delete server-side session-related files.
string session_id () id of current session
string session_name () The name of the currently accessed session, which is the name of the cookie where the client saves the session ID. Default
PHPSESSID.
array session_get_cookie_params () The details of the session associated with this session.
string session_cache_limiter () controls the client-side caching of pages using session
ini session_cache_expire () controls client cache time
bool session_destroy () Delete the file that saves session information on the server side
void session_set_cookie_params (int lifetime [, string path [, string domain [, bool
secure [, bool httponly]]]]) Set the details of the session associated with this session
bool session_set_save_handler (callback open, callback close, callback read, callback
write, callback destroy, callback gc) Define the function that handles the session, (not the default way)
bool session_regenerate_id ([bool delete_old_session]) assign a new session id

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.