Ado. Reading of most of the table operations in net

Source: Internet
Author: User
ado| data

In the development based. NET Platform database application, we generally use dataset, as the core class of Ado.net it provides us with powerful functions, and the whole looks like a small database in memory, including the DataTable, DataView, DataRow, DataColumn, constraint and DataRelation. I was a little excited when I saw it.

Here are some examples of some of my experiences to illustrate the operations that enable transactions in Ado.net, associated table updates, and multiple command objects during execution. Welcome you to Exchange, or on the blog message.

  First, preparatory work

We are familiar with the Northwind database, so take it as an example, I put the Customers (Customer table), Orders (order form), ordering details (Order Detail table) together to establish a typed dataset, The type name is Datasetorders, each table contains only some fields, and the following is in visual Studio. NET to create a screenshot:

Figure 1-1

The above set up two relationships expressed as customers-> Orders->order Details. Because the OrderID field of the Orders table is an automatic growth column, the AutoIncrementSeed and AutoIncrementStep values are set to-1, which may be obvious in the actual addition of the order, but it's no problem.

  Two Populating data sets

Create a form program to demonstrate the actual operation, the interface is as follows:

Figure 2-1

The entire application is a form whose three DataGrid is used to display data for the related tables, but they interact with each other. The other two radio boxes are used to decide how to update the data, and two buttons just like their name to complete the function.

Here we use a DataAdapter to fill the dataset, and execute the stored procedure as follows:

CREATE PROCEDURE Getcustomerordersinfo

As

SELECT customerid,companyname,contactname from Customers WHERE CustomerID like ' a% '

SELECT Orderid,orderdate,customerid from the Orders WHERE CustomerID in
(SELECT CustomerID from Customers WHERE CustomerID like ' a% ')

SELECT Orderid,productid,unitprice,quantity,discount from [order Details] WHERE OrderID in
(SELECT OrderID from the Orders WHERE CustomerID in
(SELECT CustomerID from Customers WHERE CustomerID like ' a% '))

Go

To reduce the amount of data, only the data CustomerID with ' A ' is taken. Establish the DataAccess class to manage the interaction between the form and the data tier:

Using System;
Using System.Data;
Using System.Data.SqlClient;
Using Microsoft.ApplicationBlocks.Data;
Namespace Winformtest
{
public class DataAccess
{
private string _connstring = "Data source= (local); initial catalog=northwind;uid=csharp;pwd=c#.net2004;";
Private SqlConnection _conn;
Constructors
Public DataAccess ()
{
_conn = new SqlConnection (_connstring);
}

The following function completes a single data adapter to fill the dataset

public void Fillcustomerordersinfo (Datasetorders ds)
{
SqlCommand comm = new SqlCommand ("Getcustomerordersinfo", _conn);
Comm.commandtype = CommandType.StoredProcedure;
SqlDataAdapter dataAdapter = new SqlDataAdapter (comm);
DATAADAPTER.TABLEMAPPINGS.ADD ("Table", "Customers");
DATAADAPTER.TABLEMAPPINGS.ADD ("Table1", "Orders");
DATAADAPTER.TABLEMAPPINGS.ADD ("Table2", "Order Details");
DataAdapter.Fill (DS);
}

It's easier if you use SqlHelper to populate it:

public void Fillcustomerordersinfowithsqlhelper (Datasetorders ds)
{
Sqlhelper.filldataset (_connstring,commandtype.storedprocedure, "Getcustomerordersinfo", Ds,new string[]{" Customers "," Orders "," Order Details "});
}

Fork open the topic to mention, Data Access Application Block 2.0 of the Sqlhelper.filldataset this method is more than two tables filled with errors, in fact, the logic inside is wrong, but only two tables when coincidentally, the following is from the inside section of the code:

private static void FillDataSet (SqlConnection connection, sqltransaction transaction, CommandType commandtype, string CommandText, DataSet DataSet, string[] Tablenames,
params sqlparameter[] commandparameters)

{
if (connection = = null) throw new ArgumentNullException ("Connection");
if (DataSet = null) throw new ArgumentNullException ("DataSet");
SqlCommand command = new SqlCommand ();
BOOL mustcloseconnection = false;
PrepareCommand (command, connection, transaction, CommandType, CommandText, Commandparameters, out mustcloseconnection );

using (SqlDataAdapter dataAdapter = new SqlDataAdapter (command))
{
if (tablenames!= null && tablenames.length > 0)
{
String tablename = "Table";
for (int index=0; index < tablenames.length; index++)
{
if (tablenames[index] = = NULL | | tablenames[index]. Length = = 0)
throw new ArgumentException ("the Tablenames parameter must contain a list of tables, a value was provided as NULL or EMP Ty string. "," tablenames ");

TableName + = (index + 1). ToString ()//There is an error here

}
}
DataAdapter.Fill (DataSet);
Command. Parameters.clear ();
}
if (mustcloseconnection)
Connection. Close ();
}

Here put TableName + = (index + 1). ToString ();

DATAADAPTER.TABLEMAPPINGS.ADD (index>0) (Tablename+index. ToString ()): TableName, Tablenames[index]); it will solve the problem.

Next look at the code for the form program:

public class Form1:System.Windows.Forms.Form
{
Private DataAccess _dataaccess;
Private Datasetorders _ds;
......
Constructors
Public Form1 ()
{
InitializeComponent ();
_dataaccess = new DataAccess ();
_ds = new Datasetorders ();
_ds. EnforceConstraints = false; Turn off constraint checking to improve data-filling efficiency
This.dataGridCustomers.DataSource = _ds;
This.dataGridCustomers.DataMember = _ds. Customers.tablename;
This.dataGridOrders.DataSource = _ds;
This.dataGridOrders.DataMember = _ds. Customers.tablename+ "." +_ds. Customers.childrelations[0]. RelationName;
This.dataGridOrderDetails.DataSource = _ds;
This.dataGridOrderDetails.DataMember =_ds. Customers.tablename+ "." +
_ds. Customers.childrelations[0]. Relationname+ "." +
_ds. Orders.childrelations[0]. RelationName;
}

For the dynamic Association of the three tables above, you can also use the SetDataBinding method to complete the dynamic binding of the data instead of specifying the DataSource and Datamemger properties of the datagride separately.

This.dataGridCustomers.SetDataBinding (_ds,_ds. Customers.tablename);

This.dataGridOrders.SetDataBinding (_ds,_ds. Customers.tablename+ "." +_ds. Customers.childrelations[0]. RelationName);

This.dataGridOrderDetails.SetDataBinding (_ds,_ds. Customers.tablename+ "." +
_ds. Customers.childrelations[0]. Relationname+ "." +_ds. Orders.childrelations[0]. RelationName);
}

Data padding events are handled as follows:

private void Buttonfilldata_click (object sender, System.EventArgs e)
{
_ds. Clear ();//Repopulate Data set
_dataaccess.fillcustomerordersinfo (_ds);
_dataaccess.fillcustomerordersinfowithsqlhelper (_ds);
}

To perform the event handler above, we will see that the data is displayed on the corresponding DataGrid, as shown in (Figure 2-1).

If you use a data reader to get multiple table records the following is a way to implement it (reference):

SqlCommand comm = new SqlCommand ("Getcustomerordersinfo", _conn);
Comm.commandtype = CommandType.StoredProcedure;
_conn. Open ();
SqlDataReader reader = Comm. ExecuteReader ();
Todo
{
while (reader. Read ())
{
Console.WriteLine (Reader[0]. ToString ());//Get Data code
}
}while (reader. NextResult ());
Console.ReadLine ();
_conn. Close ();



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.