In general, sqldataadapter should be used with dataset, and sqldataadapter should be used to obtain data in the database and fill it into dataset.
First, to execute a SELECT query from the SQL database, you need to establish a sqlconnection object connected to the database through the connection string, and then construct a sqldataadapter object containing the query statement. To fill in the DataSet object with the returned results of the query, you must call the fill method of sqldataadapter.
Note the following key methods:
Sqlconnection sconn = "Server = Local; database = pubs; trusted_connection = yes);"
Sqldataadapter SDA = sqldataadapter ("select * from sales", sconn );
Dataset DS = new dataset ();
SDA. Fill (DS, "sales");
SDA. Dispose ();
In this way, the sales data table in pubs is assigned to DS. Finally, disconnect the connection between SDA and the database.
There are several additional methods:
Sqldataadapter SDA = sqldataadapter ("select * from sales", sconn );
Can be written:
Sqldataadapter SDA = sqldataadapter ();
SDA. selectcommand = new sqlcommand ("select * from sales", sconn );
Dataset DS = new dataset ();
SDA. Fill (DS, "sales");
Can be written:
Dataset DS = new dataset ("sales");
SDA. Fill (DS );
Binding dataset to controls:
Generally, it is bound to the DataGrid:
Datagrid1.datasource = Ds. Tables ["sales"]. defautview; // or ds. Tables [0]. defautview;
Datagrid1.databind ();
Binding dataset to multiple data tables:
Sqlconnection sconn = "Server = Local; database = pubs; trusted_connection = yes);"
Sqldataadapter SDA = sqldataadapter ("select * from sales", sconn );
Dataset DS = new dataset ();
SDA. Fill (DS, "sales"); // enter the sales table in DS
SDA. Dispose ();
SDA. selectcommand = new sqlcommand ("select * from authors", sconn );
SDA. Fill (DS, "authors"); // enter the authors table in DS
Datagrid1.datasource = Ds. Tables ["sales"]. defaultview;
Datagrid1.databind ();
Datagrid2.datasource = Ds. Tables ["Authors"]. defaultview;
Datagrid2.databind ();
Differences between a command object and a dataadapter object:
The command object is used to run commands, and the dataadapter object is used to provide storage space for multiple commands. Dataadapter objects have four attributes: selectcommand, updatecommand, insertcommand, and deletecommand. These attributes can be saved as command objects.