Next, I sent something I wrote, Which is intermittent. I hope it will help you!
After creatingDatasetAfter the object, the following thing isDatasetFill data in a dataset. Currently, the most common data filling method is used in combination with databases.DataadapterObject FillingDataset. This method is introduced in this section, and the other two methods are introduced.
Detailed explanation
1.Pass the data in the databaseDataadapterObject FillingDataset.
This is in the databaseProgramThe most common data Filling Method in the development process. This method is mainly usedDataadapterObjectFillAndFillschemaYou can use either of the following methods to populate a dataset. The following describes how to load data from a databaseDataset.
DataadapterFillDatasetThe process is divided into two steps: first passDataadapterOfSelectcommandAttribute to retrieve the required data from the database.SelectcommandIs actuallyCommandObject. Then passDataadapterOfFillMethod to populate the Retrieved DataDataset.The procedure is as follows:
1 ).StartVisual Studio. NET.
2 ).InVisual C #. netCreate a new"ASP. NETWebsite project.Visual Studio. NETA name is automatically created:Default. aspx.
3 ).InDefault. aspx. CSCodeMake sure that the web page referencesSystem AndSystem. Data These two namespaces exist by default when they are created.
4 ).BesidesSystem,System. DataThe two namespaces also needSystem. Data. sqlclientNamespace. AvailableUsingTo reference the namespace. To do this, you do not need to restrict declarations in these namespaces in the code that follows.ImplementationThe Code is as follows:
//Reference namespace
Using system;
Using system. Data;
Using system. Data. sqlclient;
5 ).Since you want to obtain data from the database, the first step isCreate a database connection.SqlcommandObject and a connection string. The connection string in the following code is connected toSQL ServerServer. You must modify the connection string according to the environment. CreateSqlconnectionAfter the object, callOpenMethod to establish the actual database link. ImplementationThe Code is as follows:
String sconnectionstring ;//Declare a string
//Database connection string
Sconnectionstring =" Data Source =.; initial catalog = northwind; user id = sa ;";
//CreateSqlconnectionDatabase connection object
Sqlconnection conn = new sqlconnection (sconnectionstring );
//OpenConn
Conn. open ();
6 ).Next we needCreateDataadapterObject, which indicates the database andDatasetLinks between objects. It is equivalentDatasetObject To build a bridge for data to pass. You canSQLOr another type of command used to retrieve data is specifiedDataadapter Is part of the constructor object. The following example usesSQLStatement fromNorthwindDatabaseMERsTable retrieval record.ImplementationThe Code is as follows:
Sqldataadapter customer = new sqldataadapter ("select * from MERs", Conn );
7 ).Must declare and createDataset An instance of the object.Dataset Provide a name before loading any data. This name can contain several independent tables.ImplementationThe Code is as follows:
Dataset DS = new dataset ();
8 ).InSqldataadapterClass provides two data set filling methods. One isFillMethod, the other isFillschemaMethod. Both methods can load informationDataset. The difference is thatFillMethodLoad the data itself, andFillschemaMethodLoad all available metadata (such as column names, primary keys, and constraints) for a specific table ). The correct way to process data loading is to run it first.Fillschema, And then runFill.ImplementationThe Code is as follows:
Customer. fillschema (DS, schematype. source, "customers"); customer. Fill (DS, "customers ");
In fact, in many cases, onlyFillYou can also use the data filling function to load only the basic metadata required to describe the column name and data type.FillThe primary key information cannot be loaded, but this method can meet the needs of daily software development. The implementation code is as follows:
Customer. Fill (DS, "MERs ");
9 ).The data is usedDatasetOfTablesIndependentDatatableObject. If you areFillschemaAndFillYou can use this name to access the expected table.
Datatable tblcustomers ;//CreateDatatableData Table
//Replace the created data table
Tblcustomers = Ds. Tables ["customers"];
10 ). BelowUseForeachLoopDatatable"CompanyName"ColumnThe pop-up dialog box is displayed in sequence.ImplementationThe Code is as follows:
//Looping based on Behaviors
Foreach (datarow drcurrent in tblcustomers. Rows)
{
//Displayed in the pop-up dialog boxCompanyNamePowerful data information
Response. Write ("<SCRIPT> alert ('" + drcurrent ["companyName"]. tostring () + "') </SCRIPT> ");
}
11 ). Save the project. This completes a simple dataset filling operation.
All the code is given below:
String sconnectionstring ;//Declare a string
//Database connection string
Sconnectionstring = "Data Source =.; initial catalog = northwind; user id = sa ;";
//CreateSqlconnectionDatabase connection object
Sqlconnection conn = new sqlconnection (sconnectionstring );
//OpenConn
Conn. open ();
Sqldataadapter customer = new sqldataadapter ("select * from MERs", Conn );
Dataset DS = new dataset ();
//Fill a dataset
Customer. Fill (DS, "MERs ");
Datatable tblcustomers ;//CreateDatatableData Table
//Replace the created data table
Tblcustomers = Ds. Tables ["customers"];
//Looping based on Behaviors
Foreach (datarow drcurrent in tblcustomers. Rows)
{
//Displayed in the pop-up dialog boxCompanyNamePowerful data information
Response. Write ("<SCRIPT> alert ('" + drcurrent ["companyName"]. tostring () + "') </SCRIPT> ");
}
Running Effect
If you write the above Code in the createdWebProgram, click"Button"Button, the initial value is0The step is1The result is as follows:Figure9.5The displayed result.
Figure9.5Running Effect in this example
2.PassDataadapterObject operationsDatasetUpdate Database
OftenDatasetThe user data operation is completed, but the data has been modified. The modified data must be written into the database again. What should I do at this time? The traditional way of thinking is to write the data back to the corresponding table in the database. But nowDatasetIt is disconnected from the database, so how can this problem be solved?DatasetTo update the database.
In fact Ado. net2.0 Medium PassDataadapterObject operationsDatasetUpdate the database. Dataadapter Is through its Update Method Dataset To update the database. When Dataset When the data contained in the instance is changed Update Method, Dataadapter The changes are analyzed and the corresponding commands are executed ( Insert , Update Or Delete ), And use this command to update the data in the database. If Dataset In Datatable Is mapped to a single database table or generated from a single database table, you can use Commandbuilder Automatic Object generation Dataadapter Of Deletecommand , Insertcommand And Updatecommand . Use Dataadapter Object operations Dataset The following code deletes the update database. MERs Before data table 5 Row data. Implementation The Code is as follows:
String sconnectionstring ;//Declare a string
//Database connection string
Sconnectionstring =" Data Source =.; initial catalog = northwind; user id = sa ;";
//CreateSqlconnectionDatabase connection object
Sqlconnection conn = new sqlconnection (sconnectionstring );
//OpenConn
Conn. open ();
//Create and initializeSqlcommandObject
Sqldataadapter customer = new sqldataadapter ("select * from MERs", Conn );
Dataset DS = new dataset ();
//UseSqldataadapterOfFillMethod FillingDataset
Customer. Fill (DS, "MERs ");
Datatable tblcustomers ;//CreateDatatableData Table
//Replace the created data table
Tblcustomers = Ds. Tables ["customers"];
//Close data connection
Conn. Close ();
//Before deleting a data table5Row data
For (INT I = 0; I <5; ++ I)
{
DS. Tables ["MERs"]. Rows [I]. Delete ();
}
//DeleteDatasetDeleting a data tableMERsThe first row of data in
DS. Tables ["MERs"]. acceptchanges ();
Not familiarDatasetStructure and relationship with the database, many beginners often just updateDatasetThe data in the database is also updated, so when you open the database browsing and find that the data is not updated, you will be confused. Through the above introduction, the doubt should be eliminated.
3.SetXMLLoad data streams or textDataset
BecauseAdo. net2.0AndXMLFile combination, so at this timeDatasetData inXMLCreate a data stream or document. LoadXMLData Flow and documentationDatasetIs usableDatasetObjectReadxmlMethod. TheReadxmlMethod readingXMLStream or document content and load dataDataset. Based on the specifiedXmlreadmodeAnd whether the relational architecture already exists, it will also createDataset. The implementation code is as follows:
Dataset DS = new dataset ("xmlds ");
DS. readxml ("C: \ databases. xml ");