Using SQL Server with .NET and System.Data.SqlClient

These examples focus on the C# language.  If you're looking for VB.NET examples, try www.CodeProject.com.

Executing queries on a Microsoft SQL Server using SqlDataReader requires 3 basic objects (all of them in the System.Data.SqlClient namespace):

Stored Procedures vs. Dynamic SQL

If you control both the SQL server and the code accessing the server, I highly recommend that you use Stored Procedures ("sprocs") instead of dynamic SQL to service queries.  Sprocs provide key advantages over dynamic SQL:

Coding guidelines

Before we get started, I want to stress some important considerations when coding your own versions of the sample code you see here.

  1. Do not just copy and paste this code and expect it to work for you!  I have made a moderate effort to ensure that the code is correct and fairly safe, but YMMV, and as part of your due diligence you should always understand every line of code and how it impacts your application's security, performance, etc.
  2. You always need error and exception handling code--it goes hand-in-hand with the actual "mainline" code.
  3. Please, for the love of all that is holy, do not catch System.Exception!  If an exception is raised, you must handle only those exceptions you can recover from.  Yes, it takes more work, but you will reap the benefits in increased security and performance ten-fold in any project of more than a few source files.
1. SqlConnection2. SqlCommand (sproc)3. SqlCommand (text)4. SqlCommand.NonQuery (ignore the result set!)5. SqlCommand.ExecuteReaderPrintable view

Opening a connection to the SQL Server

First things first.  Before you do anything, you must create and open a connection to the SQL server that is going to be executing your query.  To do this, you need to instantiate a SqlConnection object and set its ConnectionString property (you may do so in the constructor, if you like).  ADO connection strings are documented a bit arcanely in the MSDN library, mainly due to their flexibility.  95% of the time you can get away with a simple connection string like this:

server=MyServer; database=MyDatabase; Integrated Security=SSPI

...or if you are using SQL security (bad! bad! bad!) instead of Windows Integrated security:

server=MyServer; database=MyDatabase; userid=MyUserID; password=MyPassword

Once you have created the SqlConnection, the next step is to open the connection.  To do so, just call the Open() method on your SqlConnection object:

SqlConnection conn = new SqlConnection("server=MyServer; database=MyDatabase; Integrated Security=SSPI");
conn.Open();

After you are finished with the connection, close it!  SQL connections are often limited in number by a license agreement, so you want to get in, get/send your data, and get out as soon as possible.


Do you have comments or questions about this page? I want to hear them!