Library tutorials & articles
Using ADO.NET with SQL Server
Using the DataSet
Although the DataReader is very fast and simple, in many situations, we're going to need more than just forward-only access to the results of our queries - this is where the DataSet and SqlDataAdapter classes come in. The DataSet is essentially an in-memory database, complete with multiple tables, constraints, running queries and sorting, plus the ability to persist its state to an XML file. You can use SqlDataAdapter (and its cousins OleDbDataAdapter and OdbcDataAdapter) to populate the DataSet with rows from a SQL server query. Once populated, you can make changes to the DataSet, add rows, perform sorting etc, and then use the SqlDataAdapter again to reflect these changes in the original database using appropriate UPDATE and DELETE sql statements. Depending on the available resources on your database server and the web server, relocating these operations to a disconnected model can be greatly beneficial.
Lets first take a look at how we can fill a dataset:
[C#]
// create the data adapter
SqlDataAdapter dataAdapter = new SqlDataAdapter ("SELECT userId,username FROM users ORDER BY username", sqlConn);
// create the DataSet
DataSet dataSet = new DataSet();
// fill the DataSet using our DataAdapter
dataAdapter.Fill (dataSet);
Here the SQL query is actually executed when we call the Fill method of the SqlDataAdapter - and as soon as the query is completed, the connection for the database query is closed (so the DataSet acts as "disconnected" data store). Now that we've populated the DataSet, its Tables property will be populated with DataTable objects for each table in our query. So, the following code would have the same result as our small DataReader example earlier - except we're no longer reading the results straight from the database, and can enumerate the table rows as often as we like, in any order we like.
[C#]
foreach(DataRow dataRow in dataSet.Tables["users"].Rows) {
Debug.WriteLine(dataRow["username"] + "(" + dataRow["userid"] + ")");
}
Sorting and Filtering
How about if we want to filter or sort the data further once we've retrieved it from the database? The simplest way (if we're not looking to DataBind to a control), is to use the Select method of the DataTable, which accepts two parameters - a filter expression and a sort expression - and returns an array of DataRow objects.
[C#]
DataRow[] matchingRows = dataSet.Tables["users"].Select("username like 'Bob%'","dateJoined DESC");
Another method is to use the DataView object, which is specifically designed for sorting and filtering rows, and can be used as a DataSource in its own right - so we could bind a DataGrid control to this customised "view". We can get an instance of a DataView object from the DefaultView property of our DataTable. Then, we can sets its Sort and RowFilter properties:
[C#]
DataView dataView = dataSet.Tables["users"].DefaultView;
dataView.RowFilter = "username like 'Bob%'";
dataView.Sort = "dateJoined DESC";
myDataGrid.DataSource = dataView;
//Call to DataBind needed in ASP.NET
//myDataGrid.DataBind();
Adding, Deleting & Updating Rows
Making modifications to the DataSet, and then updating the database to reflect this changes is simple, especially if we're just performing queries on one table. For the moment, lets assume that we're using a DataGrid to display our data - which means it will automatically add new rows to the DataSet for us, and allow rows to be edited or deleted without having to write any code whatsoever. All we'll need to do is "sync" the database with the modifications that take place, using the SqlDataAdapter/OleDbDataAdapter.
For this purpose, the data adapter exposes four properties - SelectCommand (which we have already set indirectly when we construct the SqlDataAdapter object), UpdateCommand, DeleteCommand and InsertCommand, and a method called Update. All we need to do is provide SqlCommand/OleDbCommand objects for these properties, and call Update - then the DataAdapter will use the appropriate commands to update the database with the changes made in the DataSet. In fact, our lives are made even easier by the existence of the SqlCommandBuilder class - which will mean we only have to write the one SELECT statement, and it will do the rest. Here's a demonstration:
[C#]
// create the data adapter
SqlDataAdapter dataAdapter = new SqlDataAdapter ("SELECT userId,username FROM users ORDER BY username", sqlConn);
// create an SqlCommandBuilder - this will automatically
generate the
// commands, and set the appropriate properties in the dataAdapter
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
// create the DataSet
DataSet dataSet = new DataSet();
// fill the DataSet using our DataAdapter into a table called users
dataAdapter.Fill (dataSet,"users");
// set the DataGrid source to the one table in our dataset
myDataGrid.DataSource = dataSet.Tables[0];
Then, when we've finished making our changes to the DataSet via the DataGrid, we call
dataAdapter.Update(dataSet);
and the database will now contain the changes we have made.
Related articles
Related discussion
-
High-Performance .NET Application Development & Architecture
by Manjot Bawa (0 replies)
-
hey developers out there
by pitsophera (0 replies)
-
Looking for .Net C# Software Developers
by sugagirisa (2 replies)
-
VS.NET/sql server installation problem
by Manjot Bawa (3 replies)
-
Connection String format between ADO and ADO.NET
by Manjot Bawa (2 replies)
Related podcasts
-
A Practical Look at Silverlight 2 Part 1
Now that Silverlight 2 is at the Olympics and making a big splash, we wanted to explore this fascinating technology more. Microsoft Silverlight 2 is a cross-browser, cross-platform, and cross-device plug-in for delivering the next generation of .NET based media experiences and rich interactive ap...
Events coming up
-
Nov
18
15 Minutes of Fame
Dresher, United States
This is a yearly tradition. We select 10 of the favorite speakers from monthly meetings, code camps, and hands on labs. Each one does a 15 minute talk on their favorite .NET technology. This is our 10th anniversary so we plan a gala event with special prizes and refreshments.
The new VSTS enables you to convert your imagination into the perfect material images on screen ! Let your mind do the thinking and VSTS will do the rest ..... http://bit.ly/izsu9
!--removed tag-->Excellant article, very meaty and precise!
Here is a little utility for helping get the precise sequence of objects correct for a particular combination of request/data type, at least for SqlClient
http://www.nicecleanexample.com/Tools/SqlBuilder/SqlClient.aspx
jk
Hi, finally getting somewhere with my understanding of ADO but am still a bit lost with my predicament.
I have an Empress (SQL) database on a Linux server that I want to link to an MS Access database on a Win2000 PC (they are both on the same closed network).
Although I have read and understood the topic and have tried and failed to get my link to work I have somehow managed to get myself stuck in a neverending loop of confusion. I think I'm trying to do too many things with too many programming languages at the minute and am one stage away from placing my underpants on my head with a pencil up each nostril and need someone to guide me through to the next stage before I implode!
Thanks
Hi Folks,
I keep getting this error when trying to connect to my sql dbase.
An error has occurred while establishing a connection to the server. When connecting to SQL Server 2005, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
I'm currently learning to use vb.net and sql server, so i am a novice. Any help would be gratefully appreciated.
kindest regards.
After spending about 6 months part-time experimenting with the 2005 pro vb.net interface using wizards, its my opinion that wizards should NOT be used to develop anything but fixed database prototypes.
I had actually started using code in 2005 but it was crashing so much that I tried the wizards.
The wizards didn't crash so much when building solutions. I thought I had finally found a code generator that actually worked. Come to find out only up to a point.
Once I started using the wizard, I had so many work arounds and crashes from attempting to change a database field that I finally gave up. Some of the crashes were so bad they actually corrupted files.
The wizards are there just to "wow" unsuspecting parties into thinking its super easy to use.
Its not. Its super easy to use exactly how they demo in the limited way of the drag-n-drop features and thats all.
Absolutly no support or demos regarding how to modify once built.
I tried chasing down the code behind the wizards but like every other code generator its so complex its propriatary and very easy to break.
Don't use the wizards as a coder. Develop everything in code.
I could suggest only to use the wizards on a fixed database and never try to modify the db or the code.
Just re-wizards everything.
Or use the wizards to dupe unsuspecting clients into thinking its easy to use.
So please, please don't waste your time using the wizards.
---------------
hello,
hey very gud article. but i am facing a problem that when i connect to SQLServer usisng C# it doesnt allowed me to connect by saying its not a valid user. as i am using Windows authentication for connecting to the SQLServer
hello,
hey very gud article. but i am facing a problem that when i connect to SQLServer usisng C# it doesnt allowed me to connect by saying its a valid user. as i am using Windows authentication for connecting to the SQLServer
dear sir,
i 'm facing some problem in insert data from an application to database using dataset. pls. help me in parameterised insert data into a datasource.
sukanta
Great article, very helpfull. Although I'm writing because I have lingering doubts on the subject in general, I've been programming with visual basic, all the way from 6.0 to 2005 and several database managers, and I've generally avoided the use of datasets, datatables, etc etc, I work writing my updates, inserts and deletes (you have to set them up anyway using datasets), and fill my datagrids using arraylists of the objects I build, which gives me certain freedom populating them, since I can manipulate the data before showing it... on the other hand, I've also found confusing the interaction between tables and datatables with an auto-numeric value, could more likely be lack of experience, but it creates dificulties that I do not have working more directly with the database itself... So my question is, mainly, why use datasets, datatables and so on? what definites advantegaes do I get from using them instead of working with the queries myself? (which by the way I hear is faster (in runtime), and cleaner...) .. Any thoughts would be welcome of course, I'm just looking for opinions...
Thanks!
Alita
Dim sqlConn As New SqlConnection(connectionString)
would now be:Dim sqlConn as New SqlClient.SqlConnection(connectionString)It was really useful in reading this article. great stuff... could have explained the update method little bit in detail.
Thanks for the good work though....
Take care,
Suresh.N
I am very happy !
I wanted to know how the asp.net database stuff exactly works.. and well here it is..
step by step.
Thnx
/mamoman
In terms of layer segregation - there's no hint of layout code here. At the most, we're setting the DataSource for a datagrid - and then presumably the .aspx page would be dealing with the layout/appearance.
I wanted to know if this article was written with inline code in mind or code-behind.
It would appear to me to be written from an inline perspective but I am new to this and may be wrong.
I am desperately looking for someone to write something that is geared more towards (what I thought was ) the Microsoft vision. Where the developer is using the full functionality of the IDE in terms of the drag and drop features and connecting the controls via the code-behind page. This would also allow for segregation between layers (presentation, business, database).
Do you know where I can find such a tutorial?
Thank you for your time.
Sincerely,
Tim
Very clear and concise, well done! Keen to read your next article on this topic...
Bravo!! James...... You wrote that article so fine....so lucid it is....Got a good insight into Ado.net.
Would like to see you going into more details on it...Well Done!!
I enjoyed this article. Clearly constructed, good basic examples, logical progression of complexity. All fairly basic stuff, but a good grounding.
Thank you!
is there anything you dont know?
This thread is for discussions of Using ADO.NET with SQL Server.