Library tutorials & articles
Using ADO.NET with SQL Server
- Introduction
- Executing a SQL query and SqlDataReader
- Stored Procedures and other queries with parameter
- Using the DataSet
- Doing without CommandBuilder & Wrapping Up
Doing without CommandBuilder & Wrapping Up
Although the CommandBuilder does a great job on simple tables, when we start using more complex SELECT statements - or simply want more control over what's going on - then its time to specify our own commands for each of the Command properties in the DataAdapter. First, we can specify the SelectCommand as usual, perhaps adding parameters for a Stored Procedure or WHERE clause.
[C#]
// create the data adapter - we'll specify the connection through our SqlCommand object
SqlDataAdapter dataAdapter = new SqlDataAdapter();
SqlCommand sqlSelectCommand = new SqlCommand("SELECT userid,username FROM users",sqlConn);
// assign to the SelectCommand property
dataAdapter.SelectCommand = sqlSelectCommand;
Now, for the INSERT, DELETE and UPDATE statements we write a generalized query with parameters - and then take advantage of another constructor for the SqlParameter object that lets us effectively bind a parameter to a column name (as obviously we won't actually know its value ourselves);
public SqlParameter (System.String parameterName, System.Data.SqlDbType dbType, System.Int32 size, System.String sourceColumn )
So, we can do the following:
[C#]
// create a new Command for our UPDATE statement
SqlCommand sqlUpdateCommand = new SqlCommand("UPDATE users SET username=@username WHERE userid=@id",sqlConn);
// add parameter to this command for @username, and bind it to the column "username"
sqlUpdateCommand.Parameters.Add("@username",SqlDbType.VarChar, 30, "username");
// create another parameter
SqlParameter sqlParam = new SqlParameter("@id",SqlDbType.Integer, 8, "userid");
sqlParam.SourceVersion = DataRowVersion.Original;
// add parameter
sqlUpdateCommand.Parameters.Add(sqlParam);
// assign to UpdateCommand
dataAdapter.UpdateCommand = sqlUpdateCommand;
Now, when the DataAdapter needs to perform an update, it will run the above command - setting @username to the value of the new username in the row that was modified. @userid, however, will be set to the original version of its value, as we set the SourceVersion property of this parameter to DataRowVersion.Original. This is generally a good idea - otherwise if we had for some reason modified the user id then we'd lose our "handle" on the row assuming userid was a primary key, and not update the correct row. If we wanted to access the new version, we would set SourceVersion to DataRowVersion.Current (its default value).
The DeleteCommand and InsertCommand properties of the DataAdapter can be set in a similar manner. Weaning Developers from the CommandBuilder on MSDN provides a good insight into further alternatives to the CommandBuilder.
Adding, Updating & Deleting Rows in a DataSet/DataTable
When we started examining the DataSet object, we skipped over the issue of actually modifying the data in our DataTable object - instead allowing the DataGrid to do the work for us. For sake of completeness, I shall give a brief summary as to how to do it "manually" here.
To add a new row to a DataTable, use the NewRow() method:
[C#]
// get a new row
DataRow newRow = myDataSet.Tables["users"].NewRow();
// set the appropriate fields here... for example
newRow["username"] = "myNewUsername";
// add to the DataTable:
myDataSet.Tables["users"].Rows.Add(newRow);
To update a row in the DataTable, you can simply modify a columns value:
myDataSet.Tables["users"].Rows[rowIndex]["realName"] = "James Crowley";
And finally, to delete one, use the Remove or RemoveAt method:
myDataSet.Tables["users"].Rows.RemoveAt(rowIndex)
or
myDataSet.Tables["users"].Rows.Remove(dataRowObject)
For more information on these, I suggest you take a look at the MSDN article Manipulating Data in a Data Table.
Conclusion
Well, that's pretty much it folks, so I'll just give a very quick overview!
-
Establishing a Connection - Use the
SqlConnectionandOleDbConnectionobjects -
Running queries - Use the
SqlCommandandOleDbCommandobjects - using theirExecuteNonQuery,ExecuteScalarandExecuteReadermethods -
Stored procedures - Just the same as above, but add appropriate
SqlParameterobjects to itsParameterscollection -
Fast forward-only data access - Use
SqlDataReaderandOleDbDataReader -
Disconnected data access - Use a DataAdapter's
Fillmethod to populate aDataSets/DataTableobject, and to then reflect changes in the database by callingUpdate
Related articles
Related discussion
-
VB.NET Type 'SqlDatabaseException' not defined
by Mulish Mehdi (1 replies)
-
An Introduction to VB.NET and Database Programming
by yen (12 replies)
-
Using ADO.NET with SQL Server
by jkoder59 (19 replies)
-
Connection String format between ADO and ADO.NET
by Sukhjinder (1 replies)
-
Creating a Database Table? [C#]
by jmcilhinney (5 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...
Related jobs
-
Microsoft .Net Architect
in AMSTERDAM (€50K-€90K per annum) -
Software Architect
in n/a (€45K-€70K per annum) -
.net developer
in Rijswijk (€2K-€4K per annum)
Events coming up
-
Dec
6
Developing AJAX Web Applications with Castle Monorail
London, United Kingdom
Monorail is the model-view-controller engine of the Castle Project, bringing many of the best ideas of Ruby on Rails to the .NET world. In this talk, David De Florinier and Gojko Adzic show how Monorail makes it easy to develop .NET based AJAX applications, and how to use the Castle Project to build Web 2.0 applications effectively. Come to this session if you are a .NET web developer. Everyone is welcome!
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.
hey pls need help wit the connection string for using sql server wit ado.net. im not gettin the code lines for the connection .please help.its urgent
Hi all,
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
Very nice article. It helped me a lot in converting some VB6 code to VB .NET 2005. The only thing I would add is a message at the top that this is for VS 2003. In VS 2005 they have made some minor changes to the syntax and the above code would not work. Ex.
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
This was still aimed with code-behind in mind. However, I've found a large number of people happily dragging and dropping components from the toolbox, or using the Microsoft wizards, with no real idea as to what each object actually does. Although the wizards are great time savers for many things, personally I still prefer writing my own logic for making calls to database stored procedures etc. But maybe I'm a control freak!
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!!
yeah. I haven't quite figured out how to get time to write more of these!
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.