<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Dotnet source code</title>
	<atom:link href="http://dotnetsourcecode.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://dotnetsourcecode.wordpress.com</link>
	<description>Dotnet Beginner Guide</description>
	<lastBuildDate>Fri, 18 Apr 2008 04:48:49 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='dotnetsourcecode.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>Dotnet source code</title>
		<link>http://dotnetsourcecode.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://dotnetsourcecode.wordpress.com/osd.xml" title="Dotnet source code" />
	<atom:link rel='hub' href='http://dotnetsourcecode.wordpress.com/?pushpress=hub'/>
		<item>
		<title>ADO.Net Objects</title>
		<link>http://dotnetsourcecode.wordpress.com/2008/04/18/adonet-objects/</link>
		<comments>http://dotnetsourcecode.wordpress.com/2008/04/18/adonet-objects/#comments</comments>
		<pubDate>Fri, 18 Apr 2008 04:48:49 +0000</pubDate>
		<dc:creator>dotnetsourcecode</dc:creator>
				<category><![CDATA[ADO.Net]]></category>

		<guid isPermaLink="false">http://dotnetsourcecode.wordpress.com/?p=11</guid>
		<description><![CDATA[ADO.Net has some differences from ADO. The main differences are: ADO.Net is connectionless, rather than connection oriented. This means ALL datasets are disconnected. It does not mean you cannot keep a connection open, it just means that all the data you work with is a copy on the client side. ADO.Net can use XML Description [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetsourcecode.wordpress.com&amp;blog=3513798&amp;post=11&amp;subd=dotnetsourcecode&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>ADO.Net has some differences from ADO. The main differences are:</p>
<ul>
<li> ADO.Net is connectionless, rather than connection oriented. This means ALL datasets are disconnected. It does not mean you cannot keep a connection open, it just means that all the data you work with is a copy on the client side.</li>
<li> ADO.Net can use XML</li>
</ul>
<p><span class="txtplain1"><strong><img src="http://images.devshed.com/af/stories/An_introduction_to_ADO/mini-image_1.JPG" alt="" width="400" height="218" /><br />
</strong></span></p>
<p align="center"><span style="font-family:Arial;font-size:85%;"></p>
<p align="left"><strong>Description </strong></p>
<p></span></p>
<ul type="disc">
<li>ADO.NET uses two types of objects to access the data in a database: <em>datasets</em>, which can contain one or more <em>data tables</em>, and <em>.NET data provider</em> objects, which include data adapters, commands, and connections.</li>
<li>A dataset stores data from the database so that it can be accessed by the application. The .NET data provider objects retrieve data from and update data in the database.</li>
<li>To retrieve data from a database and store it in a data table, a <em>data adapter</em> object issues a Select statement that’s stored in a <em>command</em> object. Next, the command object uses a <em>connection</em> object to connect to the database and retrieve the data. Then, the data is passed back to the data adapter, which stores the data in the dataset.</li>
<li>To update the data in a database based on the data in a data table, the data adapter object issues an Insert, Update, or Delete statement that’s stored in a command object. Then, the command object uses a connection to connect to the database and update the data.</li>
<li>The data provider remains connected to the database only long enough to retrieve or update the specified data. Then, it disconnects from the database and the application works with the data via the dataset object. This is referred to as a <em>disconnected data architecture.<br />
</em></li>
<li>All of the ADO.NET objects are implemented by classes in the System.Data namespace of the .NET Framework. However, the specific classes used to implement the connection, command, and data adapter objects depend on the .NET data provider you use.</li>
</ul>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/dotnetsourcecode.wordpress.com/11/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/dotnetsourcecode.wordpress.com/11/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/dotnetsourcecode.wordpress.com/11/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/dotnetsourcecode.wordpress.com/11/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/dotnetsourcecode.wordpress.com/11/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/dotnetsourcecode.wordpress.com/11/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/dotnetsourcecode.wordpress.com/11/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/dotnetsourcecode.wordpress.com/11/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/dotnetsourcecode.wordpress.com/11/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/dotnetsourcecode.wordpress.com/11/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/dotnetsourcecode.wordpress.com/11/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/dotnetsourcecode.wordpress.com/11/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/dotnetsourcecode.wordpress.com/11/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/dotnetsourcecode.wordpress.com/11/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/dotnetsourcecode.wordpress.com/11/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/dotnetsourcecode.wordpress.com/11/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetsourcecode.wordpress.com&amp;blog=3513798&amp;post=11&amp;subd=dotnetsourcecode&amp;ref=&amp;feed=1" width="1" height="1" /><div class="sharedaddy"></div>]]></content:encoded>
			<wfw:commentRss>http://dotnetsourcecode.wordpress.com/2008/04/18/adonet-objects/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/3016c9256318b7150baceec904d3723d?s=96&#38;d=identicon" medium="image">
			<media:title type="html">dotnetsourcecode</media:title>
		</media:content>

		<media:content url="http://images.devshed.com/af/stories/An_introduction_to_ADO/mini-image_1.JPG" medium="image" />
	</item>
		<item>
		<title>The SqlConnection Object</title>
		<link>http://dotnetsourcecode.wordpress.com/2008/04/18/the-sqlconnection-object/</link>
		<comments>http://dotnetsourcecode.wordpress.com/2008/04/18/the-sqlconnection-object/#comments</comments>
		<pubDate>Fri, 18 Apr 2008 04:48:19 +0000</pubDate>
		<dc:creator>dotnetsourcecode</dc:creator>
				<category><![CDATA[ADO.Net]]></category>

		<guid isPermaLink="false">http://dotnetsourcecode.wordpress.com/?p=10</guid>
		<description><![CDATA[The SqlConnection Object This lesson describes the SqlConnection object and how to connect to a data base. Here are the objectives of this lesson: Know what connection objects are used for. Learn how to instantiate a SqlConnection object. Understand how the SqlConnection object is used in applications. Comprehend the importance of effective connection lifetime management. [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetsourcecode.wordpress.com&amp;blog=3513798&amp;post=10&amp;subd=dotnetsourcecode&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<h4><strong><strong>The SqlConnection Object</strong></strong></h4>
<p>This lesson describes the SqlConnection object and how to connect to a data base. Here are the objectives of this lesson:</p>
<ul>
<li> Know what connection objects are used for.</li>
<li> Learn how to instantiate a SqlConnection object.</li>
<li> Understand how the SqlConnection object is used in applications.</li>
<li> Comprehend the importance of effective connection lifetime management.</li>
</ul>
<h4>Introduction</h4>
<p>The first thing you will need to do when interacting with a data base is to create a connection. The connection tells the rest of the ADO.NET code which data base it is talking to. It manages all of the low level logic associated with the specific data base protocols. This makes it easy for you because the most work you will have to do in code is instantiate the connection object, open the connection, and then close the connection when you are done. Because of the way that other classes in ADO.NET are built, sometimes you don&#8217;t even have to do that much work.</p>
<p>Although working with connections is very easy in ADO.NET, you need to understand connections in order to make the right decisions when coding your data access routines. Understand that a connection is a valuable resource. Sure, if you have a stand-alone client application that works on a single data base one one machine, you probably don&#8217;t care about this. However, think about an enterprise application where hundreds of users throughout a company are accessing the same data base. Each connection represents overhead and there can only be a finite amount of them. To look at a more extreme case, consider a Web site that is being hit with hundreds of thousands of hits a day. Applications that grab connections and don&#8217;t let them go can have seriously negative impacts on performance and scalability.</p>
<h4>Creating a SqlConnection Object</h4>
<p>A SqlConnection is an object, just like any other C# object. Most of the time, you just declare and instantiate the SqlConnection all at the same time, as shown below:</p>
<p><span style="font-size:85%;">SqlConnection conn = new SqlConnection(<br />
</span><span style="font-size:85%;"> &#8220;Data Source=(local);Initial          Catalog=Northwind;Integrated Security=SSPI&#8221;); </span></p>
<p>The SqlConnection object instantiated above uses a constructor with a single argument of type string. This argument is called a connection string. table 1 describes common parts of a connection string.</p>
<h6><span style="font-size:85%;">table 1. ADO.NET Connection Strings contain certain key/value pairs for specifying how to make a data base connection. They include the location, name of the database, and security credentials.</span></h6>
<table id="table3" border="1" cellspacing="0" cellpadding="0" width="100%">
<tbody>
<tr>
<th> Connection String Parameter Name</th>
<th> Description</th>
</tr>
<tr>
<td>Data Source</td>
<td>Identifies the server.  Could be local machine, machine domain name, or IP           Address.</td>
</tr>
<tr>
<td>Initial Catalog</td>
<td>Data base name.</td>
</tr>
<tr>
<td>Integrated Security</td>
<td>Set to SSPI to make connection with user&#8217;s Windows login</td>
</tr>
<tr>
<td>User ID</td>
<td>Name of user configured in SQL Server.</td>
</tr>
<tr>
<td>Password</td>
<td>Password matching SQL Server User ID.</td>
</tr>
</tbody>
</table>
<p><span style="font-family:trebuchet MS;">Integrated Security is secure when you are on a single machine doing development. However, you will often want to specify security based on a SQL Server User ID with permissions set specifically for the application you are using. The following shows a connection string, using the User ID and Password parameters:</p>
<p><span style="font-size:85%;">SqlConnection conn = new SqlConnection(<br />
</span><span style="font-size:85%;">&#8220;Data Source=DatabaseServer;Initial Catalog=Northwind;User           ID=YourUserID;Password=YourPassword&#8221;);</span></p>
<p><span style="font-size:85%;"><span style="font-size:100%;">Notice how the Data Source is set to DatabaseServer to indicate that you can identify a data base located on a different machine, over a LAN, or over the Internet. Additionally, User ID and Password replace the Integrated Security parameter.</span></span></p>
<p></span></p>
<h4>Using a SqlConnection</h4>
<p><span style="font-family:trebuchet MS;"> </span></p>
<p><span style="font-family:trebuchet MS;">The purpose of creating a SqlConnection object is so you can enable other ADO.NET code to work with a data base. Other ADO.NET objects, such as a SqlCommand and a SqlDataAdapter take a connection object as a parameter. The sequence of operations occurring in the lifetime of a SqlConnection are as follows:</span></p>
<p><span style="font-family:trebuchet MS;"> </span></p>
<ol><span style="font-family:trebuchet MS;"></p>
<li> Instantiate the SqlConnection.</li>
<li> Open the connection.</li>
<li> Pass the connection to other ADO.NET objects.</li>
<li> Perform data base operations with the other ADO.NET objects.</li>
<li> Close the connection.</li>
<p></span></ol>
<p><span style="font-family:trebuchet MS;"> </span></p>
<p><span style="font-family:trebuchet MS;">We&#8217;ve already seen how to instantiate a SqlConnection. The rest of the steps, opening, passing, using, and closing are shown in Listing 1.</span></p>
<p><span style="font-family:trebuchet MS;"> </span></p>
<h5>Listing 1.  Using a SqlConnection</h5>
<p><span style="font-family:trebuchet MS;"><span style="color:#0000ff;font-size:85%;"> using</span><span style="font-size:85%;"> System;<br />
</span><span style="color:#0000ff;font-size:85%;">using</span><span style="font-size:85%;"> System.Data;<br />
</span><span style="color:#0000ff;font-size:85%;">using</span><span style="font-size:85%;"> System.Data.SqlClient;</p>
<p></span><span style="color:#808080;font-size:85%;">///</span><span style="color:#008000;font-size:85%;"> </span> <span style="color:#808080;font-size:85%;"><br />
///</span><span style="color:#008000;font-size:85%;"> Demonstrates how to work with          SqlConnection objects<br />
</span><span style="color:#808080;font-size:85%;">///</span><span style="color:#008000;font-size:85%;"> </span> <span style="color:#808080;font-size:85%;"><br />
</span><span style="color:#0000ff;font-size:85%;">class</span><span style="font-size:85%;"> SqlConnectionDemo<br />
{<br />
</span><span style="color:#0000ff;font-size:85%;"> static</span><span style="font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;">void</span><span style="font-size:85%;"> Main()<br />
<span style="color:#0000ff;font-size:85%;"> </span>{<br />
</span><span style="color:#008000;font-size:85%;"><span style="color:#0000ff;font-size:85%;"> <span style="color:#0000ff;font-size:85%;"> </span></span>// 1. Instantiate the connection<br />
</span><span style="font-size:85%;"><span style="color:#0000ff;font-size:85%;"><span style="color:#0000ff;font-size:85%;"> </span> </span>SqlConnection conn = </span><span style="color:#0000ff;font-size:85%;">new</span><span style="font-size:85%;"> SqlConnection(<br />
<span style="color:#0000ff;font-size:85%;"><span style="color:#0000ff;font-size:85%;"> </span> <span style="color:#0000ff;font-size:85%;"> </span></span></span><span style="font-size:85%;">&#8220;Data Source=(local);Initial          Catalog=Northwind;Integrated Security=SSPI&#8221;);</p>
<p><span style="color:#0000ff;font-size:85%;"><span style="color:#0000ff;font-size:85%;"> </span> </span>SqlDataReader rdr = </span><span style="color:#0000ff;font-size:85%;">null</span><span style="font-size:85%;">;<br />
</span><span style="color:#0000ff;font-size:85%;"><br />
<span style="color:#0000ff;font-size:85%;"><span style="color:#0000ff;font-size:85%;"> </span> </span>try<br />
</span><span style="font-size:85%;"><span style="color:#0000ff;font-size:85%;"> <span style="color:#0000ff;font-size:85%;"> </span></span>{<br />
</span><span style="color:#008000;font-size:85%;"><span style="color:#0000ff;font-size:85%;"> <span style="color:#0000ff;font-size:85%;"> <span style="color:#0000ff;font-size:85%;"> </span></span></span>// 2. Open the connection<br />
</span><span style="font-size:85%;"><span style="color:#0000ff;font-size:85%;"><span style="color:#0000ff;font-size:85%;"> </span> <span style="color:#0000ff;font-size:85%;"> </span></span>conn.Open();<br />
</span><span style="color:#008000;font-size:85%;"><br />
<span style="color:#0000ff;font-size:85%;"><span style="color:#0000ff;font-size:85%;"> </span> <span style="color:#0000ff;font-size:85%;"> </span></span>// 3. Pass the connection to a command object<br />
</span><span style="font-size:85%;"><span style="color:#0000ff;font-size:85%;"><span style="color:#0000ff;font-size:85%;"> </span> <span style="color:#0000ff;font-size:85%;"> </span></span>SqlCommand cmd = </span><span style="color:#0000ff;font-size:85%;">new</span><span style="font-size:85%;"> SqlCommand(&#8220;select * from Customers&#8221;, conn);<br />
</span><span style="color:#008000;font-size:85%;"><br />
<span style="color:#0000ff;font-size:85%;"><span style="color:#0000ff;font-size:85%;"> </span> <span style="color:#0000ff;font-size:85%;"> </span></span>//<br />
<span style="color:#0000ff;font-size:85%;"><span style="color:#0000ff;font-size:85%;"> </span> <span style="color:#0000ff;font-size:85%;"> </span></span>// 4. Use the connection<br />
<span style="color:#0000ff;font-size:85%;"><span style="color:#0000ff;font-size:85%;"> </span> <span style="color:#0000ff;font-size:85%;"> </span></span>//</p>
<p><span style="color:#0000ff;font-size:85%;"><span style="color:#0000ff;font-size:85%;"> </span> <span style="color:#0000ff;font-size:85%;"> </span></span>// get query results<br />
</span><span style="font-size:85%;"><span style="color:#0000ff;font-size:85%;"><span style="color:#0000ff;font-size:85%;"> </span> <span style="color:#0000ff;font-size:85%;"> </span></span>rdr = cmd.ExecuteReader();<br />
</span><span style="color:#008000;font-size:85%;"><br />
<span style="color:#0000ff;font-size:85%;"><span style="color:#0000ff;font-size:85%;"> </span> <span style="color:#0000ff;font-size:85%;"> </span></span>// print the CustomerID of each record<br />
</span><span style="color:#0000ff;font-size:85%;"><span style="color:#0000ff;font-size:85%;"> <span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span></span>while</span><span style="font-size:85%;"> (rdr.Read())<br />
<span style="color:#0000ff;font-size:85%;"> <span style="color:#0000ff;font-size:85%;"> <span style="color:#0000ff;font-size:85%;"> </span></span></span>{<br />
<span style="color:#0000ff;font-size:85%;"> <span style="color:#0000ff;font-size:85%;"> <span style="color:#0000ff;font-size:85%;"> <span style="color:#0000ff;font-size:85%;"> </span></span></span></span>Console.WriteLine(rdr[0]);<br />
<span style="color:#0000ff;font-size:85%;"><span style="color:#0000ff;font-size:85%;"> </span> <span style="color:#0000ff;font-size:85%;"> </span></span>}<br />
<span style="color:#0000ff;font-size:85%;"><span style="color:#0000ff;font-size:85%;"> </span> </span>}<br />
</span><span style="color:#0000ff;font-size:85%;"><span style="color:#0000ff;font-size:85%;"><span style="color:#0000ff;font-size:85%;"> </span> </span>finally<br />
</span><span style="font-size:85%;"><span style="color:#0000ff;font-size:85%;"><span style="color:#0000ff;font-size:85%;"> </span> </span>{<br />
</span><span style="color:#008000;font-size:85%;"><span style="color:#0000ff;font-size:85%;"><span style="color:#0000ff;font-size:85%;"> </span> <span style="color:#0000ff;font-size:85%;"> </span></span>// close the reader<br />
</span><span style="color:#0000ff;font-size:85%;"><span style="color:#0000ff;font-size:85%;"><span style="color:#0000ff;font-size:85%;"> </span> <span style="color:#0000ff;font-size:85%;"> </span></span>if</span><span style="font-size:85%;"> (rdr != </span><span style="color:#0000ff;font-size:85%;"> null</span><span style="font-size:85%;">)<br />
<span style="color:#0000ff;font-size:85%;"><span style="color:#0000ff;font-size:85%;"> </span> <span style="color:#0000ff;font-size:85%;"> </span></span>{<br />
<span style="color:#0000ff;font-size:85%;"><span style="color:#0000ff;font-size:85%;"> </span> <span style="color:#0000ff;font-size:85%;"> <span style="color:#0000ff;font-size:85%;"> </span></span></span>rdr.Close();<br />
<span style="color:#0000ff;font-size:85%;"><span style="color:#0000ff;font-size:85%;"> </span> <span style="color:#0000ff;font-size:85%;"> </span></span>}<br />
</span><span style="color:#008000;font-size:85%;"><br />
<span style="color:#0000ff;font-size:85%;"><span style="color:#0000ff;font-size:85%;"> </span> <span style="color:#0000ff;font-size:85%;"> </span></span>// 5. Close the connection<br />
</span><span style="color:#0000ff;font-size:85%;"><span style="color:#0000ff;font-size:85%;"><span style="color:#0000ff;font-size:85%;"> </span> <span style="color:#0000ff;font-size:85%;"> </span></span>if</span><span style="font-size:85%;"> (conn != </span><span style="color:#0000ff;font-size:85%;"> null</span><span style="font-size:85%;">)<br />
<span style="color:#0000ff;font-size:85%;"><span style="color:#0000ff;font-size:85%;"> </span> <span style="color:#0000ff;font-size:85%;"> </span></span>{<br />
<span style="color:#0000ff;font-size:85%;"><span style="color:#0000ff;font-size:85%;"> </span> <span style="color:#0000ff;font-size:85%;"> <span style="color:#0000ff;font-size:85%;"> </span></span></span>conn.Close();<br />
<span style="color:#0000ff;font-size:85%;"><span style="color:#0000ff;font-size:85%;"> </span> <span style="color:#0000ff;font-size:85%;"> </span></span>}<br />
<span style="color:#0000ff;font-size:85%;"><span style="color:#0000ff;font-size:85%;"> </span> </span>}<br />
<span style="color:#0000ff;font-size:85%;"> </span>}<br />
}</span></span></p>
<p><span style="font-family:trebuchet MS;"> </span></p>
<p><span style="font-family:trebuchet MS;"> As shown in Listing 1, you open a connection by calling the <em>Open() </em>method          of the <em>SqlConnection</em> instance, <em>conn</em>. Any operations on a connection that was not yet opened will generate an exception. So, you must open the connection before using it.</span></p>
<p><span style="font-family:trebuchet MS;"> </span></p>
<p><span style="font-family:trebuchet MS;">Before using a connection, you must let the ADO.NET code know which connection it needs. In Listing 1, we set the second parameter to the <em>SqlCommand</em> object with the <em>SqlConnection</em> object, <em>conn</em>.             Any operations performed with the <em>SqlCommand</em> will use that connection.</span></p>
<p><span style="font-family:trebuchet MS;"> </span></p>
<p><span style="font-family:trebuchet MS;">The code that uses the connection is a <em>SqlCommand</em> object, which          performs a query on the Customers table.  The result set is returned as a <em>SqlDataReader</em> and the <em>while</em> loop reads the first column from each row of the result          set, which is the CustomerID column.  We&#8217;ll discuss the <em>SqlCommand</em> and <em>SqlDataReader</em> objects in later lessons.  For right now, it is          important for you to understand that these objects are using the <em>SqlConnection</em> object so they know what database to interact with.</span></p>
<p><span style="font-family:trebuchet MS;"> </span></p>
<p><span style="font-family:trebuchet MS;">When you are done using the connection object, you must close it. Failure to do so could have serious consequences in the performance and scalability of your application. There are a couple points to be made about how we closed the connection in Listing 1: the <em>Close()</em> method is called          in a <em>finally</em> block and we ensure that the connection is not null          before closing it.</span></p>
<p><span style="font-family:trebuchet MS;"> </span></p>
<p><span style="font-family:trebuchet MS;">Notice that we wrapped the ADO.NET code in a <em>try</em>/<em>finally</em> block.           As described in <a href="http://www.csharp-station.com/Tutorials/Lesson15.aspx">Lesson 15:  Introduction to           Exception Handling</a> of the C# Tutorial, <em>finally</em> blocks help guarantee that a certain piece of code will be executed, regardless of whether or not an exception is generated. Since connections are scarce system resources, you will want to make sure they are closed in <em>finally</em> blocks.</span></p>
<p><span style="font-family:trebuchet MS;"> </span></p>
<p><span style="font-family:trebuchet MS;">Another precaution you should take when closing connections is to make sure the          connection object is not <em>null</em>.  If something goes wrong when          instantiating the connection, it will be <em>null</em> and you want to make          sure you don&#8217;t try to close an invalid connection, which would generate an          exception.</span></p>
<p><span style="font-family:trebuchet MS;"> </span></p>
<p><span style="font-family:trebuchet MS;">This example showed how to use a SqlConnection object with a SqlDataReader, which required explicitly closing the connection. However, when using a disconnected data model, you don&#8217;t have to open and close the connection yourself. We&#8217;ll see how this works in a future lesson when we look at the SqlDataAdapter object.</span></p>
<p><span style="font-family:trebuchet MS;"> </span></p>
<h4><span style="font-family:trebuchet MS;">Summary</span></h4>
<p><span style="font-family:trebuchet MS;"> <span style="font-family:trebuchet MS;">SqlConnection objects let other ADO.NET code know what data base to connect to and how to make the connection. They are instantiated by passing a connection string with a set of key/value pairs that define the connection. The steps you use to manage the lifetime of a connection are create, open, pass, use, and close. Be sure to close your connection properly when you are done with it to ensure you don&#8217;t have a connection resource leak.</p>
<p></span></span></p>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/dotnetsourcecode.wordpress.com/10/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/dotnetsourcecode.wordpress.com/10/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/dotnetsourcecode.wordpress.com/10/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/dotnetsourcecode.wordpress.com/10/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/dotnetsourcecode.wordpress.com/10/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/dotnetsourcecode.wordpress.com/10/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/dotnetsourcecode.wordpress.com/10/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/dotnetsourcecode.wordpress.com/10/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/dotnetsourcecode.wordpress.com/10/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/dotnetsourcecode.wordpress.com/10/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/dotnetsourcecode.wordpress.com/10/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/dotnetsourcecode.wordpress.com/10/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/dotnetsourcecode.wordpress.com/10/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/dotnetsourcecode.wordpress.com/10/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/dotnetsourcecode.wordpress.com/10/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/dotnetsourcecode.wordpress.com/10/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetsourcecode.wordpress.com&amp;blog=3513798&amp;post=10&amp;subd=dotnetsourcecode&amp;ref=&amp;feed=1" width="1" height="1" /><div class="sharedaddy"></div>]]></content:encoded>
			<wfw:commentRss>http://dotnetsourcecode.wordpress.com/2008/04/18/the-sqlconnection-object/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/3016c9256318b7150baceec904d3723d?s=96&#38;d=identicon" medium="image">
			<media:title type="html">dotnetsourcecode</media:title>
		</media:content>
	</item>
		<item>
		<title>The SqlCommand Object</title>
		<link>http://dotnetsourcecode.wordpress.com/2008/04/18/the-sqlcommand-object/</link>
		<comments>http://dotnetsourcecode.wordpress.com/2008/04/18/the-sqlcommand-object/#comments</comments>
		<pubDate>Fri, 18 Apr 2008 04:47:38 +0000</pubDate>
		<dc:creator>dotnetsourcecode</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://dotnetsourcecode.wordpress.com/?p=9</guid>
		<description><![CDATA[The SqlCommand Object This lesson describes the SqlCommand object and how you use it to interact with a data base. Here are the objectives of this lesson: Know what a command object is. Learn how to use the ExecuteReader method to query data. Learn how to use the ExecuteNonQuery method to insert and delete data. [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetsourcecode.wordpress.com&amp;blog=3513798&amp;post=9&amp;subd=dotnetsourcecode&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<h4><strong><strong>The SqlCommand Object</strong></strong></h4>
<p>This lesson describes the SqlCommand object and how you use it to interact with a data base. Here are the objectives of this lesson:</p>
<ul>
<li> Know what a command object is.</li>
<li> Learn how to use the ExecuteReader method to query data.</li>
<li> Learn how to use the ExecuteNonQuery method to insert and delete data.</li>
<li> Learn how to use the ExecuteScalar method to return a single value.</li>
</ul>
<h4>Introduction</h4>
<p>A SqlCommand object allows you to specify what type of interaction you want to perform with a data base. For example, you can do select, insert, modify, and delete commands on rows of data in a data base table. The SqlCommand object can be used to support disconnected data management scenarios, but in this lesson we will only use the SqlCommand object alone. A later lesson on the SqlDataAdapter will explain how to implement an application that uses disconnected data. This lesson will also show you how to retrieve a single value from a data base, such as the number of records in a table.</p>
<h4>Creating a SqlCommand Object</h4>
<p>Similar to other C# objects, you instantiate a SqlCommand object via the new         instance declaration, as follows:</p>
<p><span style="font-size:85%;"> SqlCommand cmd = new SqlCommand(&#8220;select          CategoryName from Categories&#8221;, conn);</span></p>
<p>The line above is typical for instantiating a SqlCommand object. It takes a string parameter that holds the command you want to execute and a reference to a SqlConnection object. SqlCommand has a few overloads, which you will see in the examples of this tutorial.</p>
<p><span style="font-family:trebuchet MS;"> </span></p>
<h4><span style="font-family:trebuchet MS;">Querying Data</span></h4>
<p><span style="font-family:trebuchet MS;"> </span></p>
<p><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"> When using a SQL select command, you retrieve a data set for viewing. To accomplish this with a SqlCommand object, you would use the ExecuteReader method, which returns a SqlDataReader object. We&#8217;ll discuss the SqlDataReader in a future lesson. The example below shows how to use the SqlCommand object to obtain a SqlDataReader object:</span></span></p>
<p><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"> </span></span></p>
<p><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="font-size:85%;"> </span><span style="color:#008000;font-size:85%;">// 1. Instantiate a new command with a query          and connection</span><span style="font-size:85%;"><br />
SqlCommand cmd = </span><span style="color:#0000ff;font-size:85%;">new</span><span style="font-size:85%;"> SqlCommand(&#8220;select CategoryName from Categories&#8221;, conn);</p>
<p></span><span style="color:#008000;font-size:85%;">// 2. Call Execute reader to get query          results<br />
</span><span style="font-size:85%;">SqlDataReader rdr = cmd.ExecuteReader();</span></span></span></p>
<p><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"> </span></span></p>
<p><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;">In the example above, we instantiate a SqlCommand object, passing the command string and connection object to the constructor. Then we obtain a SqlDataReader object by calling the ExecuteReader method of the SqlCommand object, cmd. </span></span></p>
<p><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"> </span></span></p>
<p><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;">This code is part of the ReadData method of Listing 1 in the Putting it All          Together section later in this lesson.</span></span></p>
<p><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"> </span></span></p>
<h4><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;">Inserting Data</span></span></h4>
<p><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"> </span></span></p>
<p><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"> To insert data into a data base, use the ExecuteNonQuery method of the SqlCommand object. The following code shows how to insert data into a data base table: </span></span></span></p>
<p><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="color:#008000;font-size:85%;">// prepare command string<br />
</span><span style="color:#0000ff;font-size:85%;">string</span><span style="font-size:85%;"> insertString            = @&#8221;<br />
insert into Categories<br />
(CategoryName, Description)<br />
values (&#8216;Miscellaneous&#8217;, &#8216;Whatever doesn&#8221;t fit            elsewhere&#8217;)&#8221;;</p>
<p></span><span style="color:#008000;font-size:85%;">// 1. Instantiate a new command            with a query and connection<br />
</span><span style="font-size:85%;">SqlCommand cmd = </span><span style="color:#0000ff;font-size:85%;"> new</span><span style="font-size:85%;"> SqlCommand(insertString, conn);</p>
<p></span><span style="color:#008000;font-size:85%;">// 2. Call ExecuteNonQuery to send            command<br />
</span><span style="font-size:85%;">cmd.ExecuteNonQuery();</span> </span></span></span></p>
<p><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"> The SqlCommand instantiation is just a little different from what you&#8217;ve seen before, but it is basically the same. Instead of a literal string as the first parameter of the SqlCommand constructor, we are using a variable, insertString. The insertString variable is declared just above the SqlCommand declaration. </span></span></span></p>
<p><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"> Notice the two apostrophes (&#8221;) in the insertString text for the word &#8220;doesn&#8221;t&#8221;. This is how you escape the apostrophe to get the string to populate column properly. </span></span></span></p>
<p><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"> Another observation to make about the insert command is that we explicitly specified the columns CategoryName and Description. The Categories table has a primary key field named CategoryID. We left this out of the list because SQL Server will add this field itself. trying to add a value to a primary key field, such as CategoryID, will generate an exception. </span></span></span></p>
<p><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"> To execute this command, we simply call the ExecuteNonQuery method on the          SqlCommand instance, cmd. </span></span></span></p>
<p><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;">This code is part of the Insertdata method of Listing 1 in the Putting it All Together section later in this lesson. </span></span></span></p>
<h4><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;">Updating Data</span></span></span></h4>
<p><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"> </span></span></span></p>
<p><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"> The ExecuteNonQuery method is also used for updating data. The following code shows how to update data: </span></span></span></span></p>
<p><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="font-size:85%;"><span style="color:#008000;font-size:85%;">// prepare command string<br />
</span><span style="color:#0000ff;font-size:85%;">string</span> updateString = @&#8221;<br />
update Categories<br />
set CategoryName = &#8216;Other&#8217;<br />
where CategoryName = &#8216;Miscellaneous&#8217;&#8221;;<br />
<span style="color:#008000;font-size:85%;"><br />
// 1. Instantiate a new command with command text only<br />
</span>SqlCommand cmd = <span style="color:#0000ff;font-size:85%;">new</span> SqlCommand(updateString);<br />
<span style="color:#008000;font-size:85%;"><br />
// 2. Set the Connection property<br />
</span>cmd.Connection = conn;<br />
<span style="color:#008000;font-size:85%;"><br />
// 3. Call ExecuteNonQuery to send command<br />
</span>cmd.ExecuteNonQuery();</span> </span></span></span></span></p>
<p><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"> Again, we put the SQL command into a string variable, but this time we used a different SqlCommand constructor that takes only the command. In step 2, we assign the SqlConnection object, conn, to the Connection property of the SqlCommand object, cmd. </span></span></span></span></p>
<p><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"> This could have been done with the same constructor used for the insert command, with two parameters. It demonstrates that you can change the connection object assigned to a command at any time. </span></span></span></span></p>
<p><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"> The ExecuteNonQuery method performs the update command. </span></span></span></span></p>
<p><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;">This code is part of the UpdateData method of Listing 1 in the Putting it All Together section later in this lesson. </span></span></span></span></p>
<h4><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;">Deleting Data</span></span></span></span></h4>
<p><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"> </span></span></span></span></p>
<p><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"> You can also delete data using the ExecuteNonQuery method. The following example shows how to delete a record from a data base with the ExecuteNonQuery method: </span></span></span></span></span></p>
<p><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="font-size:85%;"><span style="color:#008000;font-size:85%;">// prepare command string<br />
</span><span style="color:#0000ff;font-size:85%;">string</span> deleteString = @&#8221;<br />
delete from Categories<br />
where CategoryName = &#8216;Other&#8217;&#8221;;<br />
<span style="color:#008000;font-size:85%;"><br />
// 1. Instantiate a new command<br />
</span>SqlCommand cmd = <span style="color:#0000ff;font-size:85%;">new</span> SqlCommand();<br />
<span style="color:#008000;font-size:85%;"><br />
// 2. Set the CommandText property<br />
</span>cmd.CommandText = deleteString;<br />
<span style="color:#008000;font-size:85%;"><br />
// 3. Set the Connection property<br />
</span>cmd.Connection = conn;<br />
<span style="color:#008000;font-size:85%;"><br />
// 4. Call ExecuteNonQuery to send command<br />
</span>cmd.ExecuteNonQuery();</span> </span></span></span></span></span></p>
<p><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"> This example uses the SqlCommand constructor with no parameters. Instead, it explicity sets the CommandText and Connection properties of the SqlCommand object, cmd. </span></span></span></span></span></p>
<p><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"> We could have also used either of the two previous SqlCommand constructor overloads, used for the insert or update command, with the same result. This demonstrates that you can change both the command text and the connection object at any time. </span></span></span></span></span></p>
<p><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"> The ExecuteNonQuery method call sends the command to the data base. </span></span></span></span></span></p>
<p><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;">This code is part of the DeleteData method of Listing 1 in the Putting it All Together section later in this lesson. </span></span></span></span></span></p>
<h4><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;">Getting Single values</span></span></span></span></span></h4>
<p><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"> <span style="font-family:trebuchet MS;"> </span></span></span></span></span></span></p>
<p><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"> Sometimes all you need from a data base is a single value, which could be a count, sum, average, or other aggregated value from a data set. Performing an ExecuteReader and calculating the result in your code is not the most efficient way to do this. The best choice is to let the data base perform the work and return just the single value you need. The following example shows how to do this with the ExecuteScalar method: </span></span></span></span></span></span></p>
<p><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="font-size:85%;"><span style="color:#008000;font-size:85%;">// 1. Instantiate a new command<br />
</span>SqlCommand cmd = <span style="color:#0000ff;font-size:85%;">new</span> SqlCommand(&#8220;select                  count(*) from Categories&#8221;, conn);<br />
<span style="color:#008000;font-size:85%;"><br />
// 2. Call ExecuteNonQuery to send command<br />
</span><span style="color:#0000ff;font-size:85%;">int </span>count = (<span style="color:#0000ff;font-size:85%;">int</span>)cmd.ExecuteScalar();</span> </span></span></span></span></span></span></p>
<p><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"> The query in the SqlCommand constructor obtains the count of all records from the Categories table. This query will only return a single value. The ExecuteScalar method in step 2 returns this value. Since the return type of ExecuteScalar is type object, we use a cast operator to convert the value to int. </span></span></span></span></span></span></p>
<p><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;">This code is part of the GetNumberOfRecords method of Listing 1 in the Putting it All Together section later in this lesson. </span></span></span></span></span></span></p>
<h4><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;">Putting it All Together</span></span></span></span></span></span></h4>
<p><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"> <span style="font-family:trebuchet MS;"> </span></span></span></span></span></span></span></p>
<p><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"> For simplicity, we showed snippets of code in previous sections to demonstrate the applicable techniques</span> </span> </span> </span> </span>. It is also useful to have an entire code listing to see how this code is used in a working program. Listing 1 shows all of the code used in this example, along with a driver in the Main method to produce formatted output.</span></span></p>
<p><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"> </span></span></p>
<h5><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;">Listing 1.  SqlConnection Demo</span></span></h5>
<p><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"> <span style="font-family:trebuchet MS;"> </span></span></span></p>
<p><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="font-size:85%;"><span style="font-size:85%;"><span style="color:#0000ff;font-size:85%;"> using</span><span style="font-size:85%;"> System;<br />
</span><span style="color:#0000ff;font-size:85%;">using</span><span style="font-size:85%;"> System.Data;<br />
</span><span style="color:#0000ff;font-size:85%;">using</span><span style="font-size:85%;"> System.Data.SqlClient;</p>
<p></span><span style="color:#808080;font-size:85%;">///</span><span style="color:#008000;font-size:85%;"> </span><span style="color:#808080;font-size:85%;"><br />
///</span><span style="color:#008000;font-size:85%;"> Demonstrates how to work with             SqlCommand objects<br />
</span><span style="color:#808080;font-size:85%;">///</span><span style="color:#008000;font-size:85%;"> </span><span style="color:#808080;font-size:85%;"><br />
</span><span style="color:#0000ff;font-size:85%;">class</span><span style="font-size:85%;"> SqlCommandDemo<br />
{<br />
SqlConnection conn;<br />
</span><span style="color:#0000ff;font-size:85%;"><br />
</span><span style="font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> public</span><span style="font-size:85%;"> SqlCommandDemo()<br />
{<br />
</span><span style="color:#008000;font-size:85%;"> // Instantiate the connection<br />
</span><span style="font-size:85%;"> </span> conn = <span style="color:#0000ff;font-size:85%;">new</span> SqlConnection(<br />
&#8220;Data            Source=(local);Initial Catalog=Northwind;Integrated Security=SSPI&#8221;);<br />
<span style="font-size:85%;"> </span>}<br />
<span style="color:#008000;font-size:85%;"><br />
</span><span style="font-size:85%;"> </span><span style="color:#008000;font-size:85%;"> // call methods that demo SqlCommand capabilities<br />
</span><span style="font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> static</span> <span style="color:#0000ff;font-size:85%;">void</span> Main()<br />
<span style="font-size:85%;"> </span>{<br />
<span style="font-size:85%;"> </span>SqlCommandDemo            scd = <span style="color:#0000ff;font-size:85%;">new</span> SqlCommandDemo();</p>
<p><span style="font-size:85%;"> </span>Console.WriteLine();<br />
<span style="font-size:85%;"> </span>Console.WriteLine(&#8220;Categories            Before Insert&#8221;);<br />
<span style="font-size:85%;"> </span>Console.WriteLine(&#8220;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8221;);<br />
<span style="color:#008000;font-size:85%;"><br />
</span><span style="font-size:85%;"> </span> <span style="color:#008000;font-size:85%;">// use ExecuteReader method<br />
</span><span style="font-size:85%;"> </span> scd.ReadData();<br />
<span style="color:#008000;font-size:85%;"><br />
</span><span style="font-size:85%;"> </span> <span style="color:#008000;font-size:85%;">// use ExecuteNonQuery method for Insert<br />
</span><span style="font-size:85%;"> </span> scd.Insertdata();<br />
<span style="font-size:85%;"> </span>Console.WriteLine();<br />
<span style="font-size:85%;"> </span>Console.WriteLine(&#8220;Categories            After Insert&#8221;);<br />
<span style="font-size:85%;"> </span>Console.WriteLine(&#8220;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8221;);</p>
<p><span style="font-size:85%;"> </span>scd.ReadData();</p>
<p><span style="font-size:85%;"> </span><span style="color:#008000;font-size:85%;"> // use ExecuteNonQuery method for Update<br />
</span><span style="font-size:85%;"> </span> scd.UpdateData();</p>
<p><span style="font-size:85%;"> </span>Console.WriteLine();<br />
<span style="font-size:85%;"> </span>Console.WriteLine(&#8220;Categories            After Update&#8221;);<br />
<span style="font-size:85%;"> </span>Console.WriteLine(&#8220;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8221;);</p>
<p><span style="font-size:85%;"> </span>scd.ReadData();</p>
<p><span style="font-size:85%;"> </span><span style="color:#008000;font-size:85%;"> // use ExecuteNonQuery method for Delete<br />
</span><span style="font-size:85%;"> </span> scd.DeleteData();</p>
<p><span style="font-size:85%;"> </span>Console.WriteLine();<br />
<span style="font-size:85%;"> </span>Console.WriteLine(&#8220;Categories            After Delete&#8221;);<br />
<span style="font-size:85%;"> </span>Console.WriteLine(&#8220;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8221;);</p>
<p><span style="font-size:85%;"> </span>scd.ReadData();</p>
<p><span style="font-size:85%;"> </span><span style="color:#008000;font-size:85%;"> // use ExecuteScalar method<br />
</span><span style="font-size:85%;"> </span> <span style="color:#0000ff;font-size:85%;">int</span> numberOfRecords =            scd.GetNumberOfRecords();</p>
<p><span style="font-size:85%;"> </span>Console.WriteLine();<br />
<span style="font-size:85%;"> </span>Console.WriteLine(&#8220;Number            of Records: {0}&#8221;, numberOfRecords);<br />
<span style="font-size:85%;"> </span>}</p>
<p><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#808080;font-size:85%;"> ///</span><span style="color:#008000;font-size:85%;"> </span><span style="color:#808080;font-size:85%;"><br />
</span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#808080;font-size:85%;"> ///</span><span style="color:#008000;font-size:85%;"> use ExecuteReader method<br />
</span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#808080;font-size:85%;"> ///</span><span style="color:#008000;font-size:85%;"> </span><span style="color:#808080;font-size:85%;"><br />
</span><span style="color:#0000ff;font-size:85%;"> public</span> <span style="color:#0000ff;font-size:85%;">void</span> ReadData()<br />
<span style="color:#0000ff;font-size:85%;"> </span>{<br />
<span style="color:#0000ff;font-size:85%;"> </span><span style="font-size:85%;"> </span>SqlDataReader rdr = <span style="color:#0000ff;font-size:85%;">null</span>;<br />
<span style="color:#0000ff;font-size:85%;"><br />
</span><span style="font-size:85%;"> <span style="color:#0000ff;font-size:85%;"> </span></span><span style="color:#0000ff;font-size:85%;">try<br />
</span><span style="font-size:85%;"> <span style="color:#0000ff;font-size:85%;"> </span></span>{<br />
<span style="font-size:85%;"> <span style="color:#0000ff;font-size:85%;"> </span></span><span style="color:#008000;font-size:85%;">// Open the             connection<br />
</span><span style="font-size:85%;"> </span> <span style="color:#0000ff;font-size:85%;"> </span>conn.Open();<br />
<span style="color:#008000;font-size:85%;"><br />
</span><span style="font-size:85%;"> <span style="color:#0000ff;font-size:85%;"> </span></span><span style="color:#008000;font-size:85%;">// 1.             Instantiate a new command with a query and connection<br />
</span><span style="font-size:85%;"> <span style="color:#0000ff;font-size:85%;"> </span></span>SqlCommand cmd = <span style="color:#0000ff;font-size:85%;"> new</span> SqlCommand(&#8220;select CategoryName from Categories&#8221;, conn);<br />
<span style="color:#008000;font-size:85%;"><br />
</span><span style="font-size:85%;"> <span style="color:#0000ff;font-size:85%;"> </span> </span><span style="color:#008000;font-size:85%;">// 2.             Call Execute reader to get query results<br />
</span><span style="font-size:85%;"> <span style="color:#0000ff;font-size:85%;"> </span> </span>rdr = cmd.ExecuteReader();</p>
<p><span style="font-size:85%;"> <span style="color:#0000ff;font-size:85%;"> </span> </span><span style="color:#008000;font-size:85%;">//             print the CategoryName of each record<br />
</span><span style="font-size:85%;"> <span style="color:#0000ff;font-size:85%;"> </span> </span><span style="color:#0000ff;font-size:85%;">while</span> (rdr.Read())<br />
<span style="font-size:85%;"> <span style="color:#0000ff;font-size:85%;"> </span> </span>{<br />
<span style="font-size:85%;"> <span style="color:#0000ff;font-size:85%;"> </span> </span>Console.WriteLine(rdr[0]);<br />
<span style="font-size:85%;"> <span style="color:#0000ff;font-size:85%;"> </span> </span>}<br />
<span style="font-size:85%;"> <span style="color:#0000ff;font-size:85%;"> </span> </span>}<br />
<span style="font-size:85%;"> <span style="color:#0000ff;font-size:85%;"> </span> </span><span style="color:#0000ff;font-size:85%;">finally<br />
</span><span style="font-size:85%;"> <span style="color:#0000ff;font-size:85%;"> </span> </span>{<br />
<span style="font-size:85%;"> <span style="color:#0000ff;font-size:85%;"> </span> </span><span style="color:#008000;font-size:85%;">// close the reader<br />
</span><span style="font-size:85%;"> <span style="color:#0000ff;font-size:85%;"> </span> </span><span style="color:#0000ff;font-size:85%;">if</span> (rdr != <span style="color:#0000ff;font-size:85%;">null</span>)<br />
<span style="font-size:85%;"> <span style="color:#0000ff;font-size:85%;"> </span> </span>{<br />
<span style="font-size:85%;"> <span style="color:#0000ff;font-size:85%;"> </span> </span>rdr.Close();<br />
<span style="font-size:85%;"> <span style="color:#0000ff;font-size:85%;"> </span> </span>}<br />
<span style="color:#008000;font-size:85%;"><br />
</span><span style="font-size:85%;"> <span style="color:#0000ff;font-size:85%;"> </span> </span><span style="color:#008000;font-size:85%;"> // Close the connection<br />
</span><span style="font-size:85%;"> <span style="color:#0000ff;font-size:85%;"> </span> </span><span style="color:#0000ff;font-size:85%;"> if</span> (conn != <span style="color:#0000ff;font-size:85%;">null</span>)<br />
<span style="font-size:85%;"> <span style="color:#0000ff;font-size:85%;"> </span> </span>{<br />
<span style="font-size:85%;"> <span style="color:#0000ff;font-size:85%;"> </span> </span>conn.Close();<br />
<span style="font-size:85%;"> <span style="color:#0000ff;font-size:85%;"> </span> </span>}<br />
<span style="font-size:85%;"> <span style="color:#0000ff;font-size:85%;"> </span> </span>}<br />
<span style="color:#0000ff;font-size:85%;"> </span>}</p>
<p><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#808080;font-size:85%;"> ///</span><span style="color:#008000;font-size:85%;"> </span><span style="color:#808080;font-size:85%;"><br />
</span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#808080;font-size:85%;"> ///</span><span style="color:#008000;font-size:85%;"> use ExecuteNonQuery method for Insert<br />
</span><span style="color:#0000ff;font-size:85%;"> </span><span style="font-size:85%;"> <span style="color:#808080;font-size:85%;">///</span><span style="color:#008000;font-size:85%;"> </span> <span style="color:#808080;font-size:85%;"><br />
</span><span style="color:#0000ff;font-size:85%;"> </span></span> <span style="color:#0000ff;font-size:85%;">public</span> <span style="color:#0000ff;font-size:85%;">void</span> Insertdata()<br />
<span style="color:#0000ff;font-size:85%;"> </span>{<br />
<span style="color:#0000ff;font-size:85%;"> try<br />
</span><span style="color:#0000ff;font-size:85%;"> </span>{<br />
<span style="color:#0000ff;font-size:85%;"> </span> <span style="color:#0000ff;font-size:85%;"> </span><span style="color:#008000;font-size:85%;"> // Open the connection<br />
</span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span>conn.Open();<br />
<span style="color:#008000;font-size:85%;"><br />
</span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#008000;font-size:85%;">// prepare command string<br />
</span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> string</span> insertString = @&#8221;<br />
<span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span>insert into            Categories<br />
<span style="color:#0000ff;font-size:85%;"> </span> <span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span>(CategoryName, Description)<br />
<span style="color:#0000ff;font-size:85%;"> </span> <span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span>values (&#8216;Miscellaneous&#8217;, &#8216;Whatever doesn&#8221;t fit            elsewhere&#8217;)&#8221;;<br />
<span style="color:#008000;font-size:85%;"><br />
</span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#008000;font-size:85%;">// 1. Instantiate a new command with a query             and connection<br />
</span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span>SqlCommand cmd = <span style="color:#0000ff;font-size:85%;">new</span> SqlCommand(insertString,            conn);<br />
<span style="color:#008000;font-size:85%;"><br />
</span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#008000;font-size:85%;">// 2. Call ExecuteNonQuery to send command<br />
</span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span>cmd.ExecuteNonQuery();<br />
<span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span>}<br />
<span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> finally<br />
</span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span>{<br />
<span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#008000;font-size:85%;"> // Close the connection<br />
</span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> if</span> (conn != <span style="color:#0000ff;font-size:85%;">null</span>)<br />
<span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span>{<br />
<span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span>conn.Close();<br />
<span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span> }<br />
<span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span>}<br />
<span style="color:#0000ff;font-size:85%;"> </span>}<br />
<span style="color:#808080;font-size:85%;"><br />
</span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#808080;font-size:85%;"> ///</span><span style="color:#008000;font-size:85%;"> </span><span style="color:#808080;font-size:85%;"><br />
</span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#808080;font-size:85%;"> ///</span><span style="color:#008000;font-size:85%;"> use ExecuteNonQuery method for Update<br />
</span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#808080;font-size:85%;"> ///</span><span style="color:#008000;font-size:85%;"> </span><span style="color:#808080;font-size:85%;"><br />
</span><span style="color:#0000ff;font-size:85%;"> public</span> <span style="color:#0000ff;font-size:85%;">void</span> UpdateData()<br />
<span style="color:#0000ff;font-size:85%;"> </span>{<br />
<span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> try<br />
</span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span>{<br />
<span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#008000;font-size:85%;"> // Open the connection<br />
</span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span>conn.Open();<br />
<span style="color:#008000;font-size:85%;"><br />
</span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#008000;font-size:85%;"> // prepare command string<br />
</span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> string</span> updateString            = @&#8221;<br />
<span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span>update Categories<br />
<span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span>set CategoryName = &#8216;Other&#8217;<br />
<span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span>where CategoryName = &#8216;Miscellaneous&#8217;&#8221;;<br />
<span style="color:#008000;font-size:85%;"><br />
</span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#008000;font-size:85%;">// 1. Instantiate a new command with command             text only<br />
</span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span>SqlCommand cmd = <span style="color:#0000ff;font-size:85%;">new</span> SqlCommand(updateString);</p>
<p><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#008000;font-size:85%;"> // 2. Set the Connection property<br />
</span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span>cmd.Connection = conn;<br />
<span style="color:#008000;font-size:85%;"><br />
</span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#008000;font-size:85%;"> // 3. Call ExecuteNonQuery to send command<br />
</span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span>cmd.ExecuteNonQuery();<br />
<span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span>}<br />
<span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> finally<br />
</span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span>{<br />
<span style="color:#0000ff;font-size:85%;"> </span> <span style="color:#0000ff;font-size:85%;"> </span><span style="color:#008000;font-size:85%;"> // Close the connection<br />
</span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> if</span> (conn != <span style="color:#0000ff;font-size:85%;">null</span>)<br />
<span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span>{<br />
<span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span>conn.Close();<br />
<span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span>}<br />
<span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span>}<br />
<span style="color:#0000ff;font-size:85%;"> </span>}<br />
<span style="color:#808080;font-size:85%;"><br />
</span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#808080;font-size:85%;"> ///</span><span style="color:#008000;font-size:85%;"> </span><span style="color:#808080;font-size:85%;"><br />
</span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#808080;font-size:85%;"> ///</span><span style="color:#008000;font-size:85%;"> use ExecuteNonQuery method for Delete<br />
</span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#808080;font-size:85%;"> ///</span><span style="color:#008000;font-size:85%;"> </span><span style="color:#808080;font-size:85%;"><br />
</span><span style="color:#0000ff;font-size:85%;"> public</span> <span style="color:#0000ff;font-size:85%;">void</span> DeleteData()<br />
<span style="color:#0000ff;font-size:85%;"> </span>{<br />
<span style="color:#0000ff;font-size:85%;"> try<br />
</span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span>{<br />
<span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#008000;font-size:85%;"> // Open the connection<br />
</span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span>conn.Open();<br />
<span style="color:#008000;font-size:85%;"><br />
</span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#008000;font-size:85%;">// prepare command string<br />
</span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> string</span> deleteString = @&#8221;<br />
<span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span>delete from            Categories<br />
<span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span>where CategoryName = &#8216;Other&#8217;&#8221;;<br />
<span style="color:#008000;font-size:85%;"><br />
</span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#008000;font-size:85%;">// 1. Instantiate a new command<br />
</span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span>SqlCommand cmd            = <span style="color:#0000ff;font-size:85%;">new</span> SqlCommand();<br />
<span style="color:#008000;font-size:85%;"><br />
</span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#008000;font-size:85%;">// 2. Set the CommandText property<br />
</span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span>cmd.CommandText = deleteString;<br />
<span style="color:#008000;font-size:85%;"><br />
</span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#008000;font-size:85%;">// 3. Set the Connection property<br />
</span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span>cmd.Connection = conn;<br />
<span style="color:#008000;font-size:85%;"><br />
</span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#008000;font-size:85%;">// 4. Call ExecuteNonQuery to send command<br />
</span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span>cmd.ExecuteNonQuery();<br />
<span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span>}<br />
<span style="color:#0000ff;font-size:85%;"> finally<br />
</span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span>{<br />
<span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#008000;font-size:85%;"> // Close the connection<br />
</span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> if</span> (conn != <span style="color:#0000ff;font-size:85%;">null</span>)<br />
<span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span>{<br />
<span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span>conn.Close();<br />
<span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span>}<br />
<span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span>}<br />
<span style="color:#0000ff;font-size:85%;"> </span>}</p>
<p><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#808080;font-size:85%;"> ///</span><span style="color:#008000;font-size:85%;"> </span><span style="color:#808080;font-size:85%;"><br />
</span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#808080;font-size:85%;"> ///</span><span style="color:#008000;font-size:85%;"> use ExecuteScalar method<br />
</span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#808080;font-size:85%;"> ///</span><span style="color:#008000;font-size:85%;"> </span><span style="color:#808080;font-size:85%;"><br />
</span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#808080;font-size:85%;"> ///</span><span style="color:#008000;font-size:85%;"> </span><span style="color:#808080;font-size:85%;"> </span><span style="color:#008000;font-size:85%;">number of records</span><span style="color:#808080;font-size:85%;"><br />
</span><span style="color:#0000ff;font-size:85%;"> public</span> <span style="color:#0000ff;font-size:85%;">int</span> GetNumberOfRecords()<br />
<span style="color:#0000ff;font-size:85%;"> </span>{<br />
<span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> int</span> count = -1;<br />
<span style="color:#0000ff;font-size:85%;"><br />
</span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> try<br />
</span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span>{<br />
<span style="color:#0000ff;font-size:85%;"> </span> <span style="color:#0000ff;font-size:85%;"> </span><span style="color:#008000;font-size:85%;"> // Open the connection<br />
</span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span>conn.Open();<br />
<span style="color:#008000;font-size:85%;"><br />
</span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#008000;font-size:85%;"> // 1. Instantiate a new command<br />
</span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span>SqlCommand cmd = <span style="color:#0000ff;font-size:85%;">new</span> SqlCommand(&#8220;select            count(*) from Categories&#8221;, conn);<br />
<span style="color:#008000;font-size:85%;"><br />
</span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#008000;font-size:85%;">// 2. Call ExecuteNonQuery to send command<br />
</span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span>count = (<span style="color:#0000ff;font-size:85%;">int</span>)cmd.ExecuteScalar();<br />
<span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span>}<br />
<span style="color:#0000ff;font-size:85%;"> finally<br />
</span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span>{<br />
<span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#008000;font-size:85%;"> // Close the connection<br />
</span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> if</span> (conn != <span style="color:#0000ff;font-size:85%;">null</span>)<br />
<span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span>{<br />
<span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span>conn.Close();<br />
<span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span>}<br />
<span style="color:#0000ff;font-size:85%;"> </span><span style="color:#0000ff;font-size:85%;"> </span>}<br />
<span style="color:#0000ff;font-size:85%;"> return</span> count;<br />
<span style="color:#0000ff;font-size:85%;"> </span>}<br />
}</span></span></span></span></span></p>
<p><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"> </span></span></span></p>
<p><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;">In Listing 1, the SqlConnection object is instantiated in the SqlCommandDemo structure. This is okay because the object itself will be cleaned up when the CLR garbage collector executes. What is important is that we close the connection when we are done using it. This program opens the connection in a try block and closes it in a finally block in each method.</span></span></span></p>
<p><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"> </span></span></span></p>
<p><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;">The ReadData method displays the contents of the CategoryName column of the Categories table. We use it several times in the Main method to show the current status of the Categories table, which changes after each of the insert, update, and delete commands. Because of this, it is convenient to reuse to show you the effects after each method call.</span></span></span></p>
<p><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"> </span> </span></span></p>
<h4><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;">Summary</span></span></h4>
<p><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"> <span style="font-family:trebuchet MS;"> </span></span></span></p>
<p><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;"><span style="font-family:trebuchet MS;">A SqlCommand object allows you to query and send commands to a data base. It has methods that are specialized for different commands. The ExecuteReader method returns a SqlDataReader object for viewing the results of a select query. For insert, update, and delete SQL commands, you use the ExecuteNonQuery method. If you only need a single aggregate value from a query, the ExecuteScalar is the best choice.</span></span></span></p>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/dotnetsourcecode.wordpress.com/9/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/dotnetsourcecode.wordpress.com/9/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/dotnetsourcecode.wordpress.com/9/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/dotnetsourcecode.wordpress.com/9/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/dotnetsourcecode.wordpress.com/9/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/dotnetsourcecode.wordpress.com/9/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/dotnetsourcecode.wordpress.com/9/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/dotnetsourcecode.wordpress.com/9/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/dotnetsourcecode.wordpress.com/9/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/dotnetsourcecode.wordpress.com/9/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/dotnetsourcecode.wordpress.com/9/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/dotnetsourcecode.wordpress.com/9/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/dotnetsourcecode.wordpress.com/9/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/dotnetsourcecode.wordpress.com/9/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/dotnetsourcecode.wordpress.com/9/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/dotnetsourcecode.wordpress.com/9/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetsourcecode.wordpress.com&amp;blog=3513798&amp;post=9&amp;subd=dotnetsourcecode&amp;ref=&amp;feed=1" width="1" height="1" /><div class="sharedaddy"></div>]]></content:encoded>
			<wfw:commentRss>http://dotnetsourcecode.wordpress.com/2008/04/18/the-sqlcommand-object/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/3016c9256318b7150baceec904d3723d?s=96&#38;d=identicon" medium="image">
			<media:title type="html">dotnetsourcecode</media:title>
		</media:content>
	</item>
		<item>
		<title>Reading Data with the SqlDataReader</title>
		<link>http://dotnetsourcecode.wordpress.com/2008/04/18/reading-data-with-the-sqldatareader/</link>
		<comments>http://dotnetsourcecode.wordpress.com/2008/04/18/reading-data-with-the-sqldatareader/#comments</comments>
		<pubDate>Fri, 18 Apr 2008 04:46:14 +0000</pubDate>
		<dc:creator>dotnetsourcecode</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://dotnetsourcecode.wordpress.com/?p=8</guid>
		<description><![CDATA[Reading Data with the SqlDataReader This lesson explains how to read data with a SqlDataReader object. Here are the objectives of this lesson: Learn what a SqlDataReader is used for. Know how to read data using a SqlDataReader. Understand the need to close a SqlDataReader. Introduction A SqlDataReader is a type that is good for [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetsourcecode.wordpress.com&amp;blog=3513798&amp;post=8&amp;subd=dotnetsourcecode&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<h4><strong><strong>Reading Data with the SqlDataReader</strong></strong></h4>
<p>This lesson explains how to read data with a SqlDataReader object.  Here         are the objectives of this lesson:</p>
<ul>
<li> Learn what a SqlDataReader is used for.</li>
<li> Know how to read data using a SqlDataReader.</li>
<li> Understand the need to close a SqlDataReader.</li>
</ul>
<h4>Introduction</h4>
<p>A SqlDataReader is a type that is good for reading data in the most efficient manner possible. You can *not* use it for writing data. SqlDataReaders are often described as fast-forward firehose-like streams of data.</p>
<p>You can read from SqlDataReader objects in a forward-only sequential manner. Once you&#8217;ve read some data, you must save it because you will not be able to go back and read it again.</p>
<p>The forward only design of the SqlDataReader is what enables it to be fast. It doesn&#8217;t have overhead associated with traversing the data or writing it back to the data source. Therefore, if your only requirement for a group of data is for reading one time and you want the fastest method possible, the SqlDataReader is the best choice. Also, if the amount of data you need to read is larger than what you would prefer to hold in memory beyond a single call, then the streaming behavior of the SqlDataReader would be a good choice.</p>
<p>Note: Observe that I used the term &#8220;one time&#8221; in the previous paragraph when discussing the reasons why you would use a SqlDataReader. As with anything, there are exceptions. In many cases, it is more efficient to use a cached DataSet. While caching is outside the scope of this tutorial, we will discuss using DataSet objects in the next lesson.</p>
<h4>Creating a SqlDataReader Object</h4>
<p>Getting an instance of a SqlDataReader is a little different than the way you instantiate other ADO.NET objects. You must call <em>ExecuteReader</em> on         a command object, like this:</p>
<p><span style="font-size:85%;"> SqlDataReader rdr = cmd.ExecuteReader();</span></p>
<p>The <em>ExecuteReader</em> method of the SqlCommand object, <em>cmd</em> , returns a SqlDataReader instance. Creating a SqlDataReader with the new operator doesn&#8217;t do anything for you. As you learned in previous lessons, the SqlCommand object references the connection and the SQL statement necessary for the SqlDataReader to obtain data.</p>
<h4>Reading Data</h4>
<p>previous lessons contained code that used a SqlDataReader, but the discussion was delayed so we could focus on the specific subject of that particular lesson. This lesson builds from what you&#8217;ve seen and explains how to use the SqlDataReader.</p>
<p>As explained earlier, the SqlDataReader returns data via a sequential stream. To read this data, you must pull data from a table row-by-row. Once a row has been read, the previous row is no longer available. To read that row again, you would have to create a new instance of the SqlDataReader and read through the data stream again.</p>
<p>The typical method of reading from the data stream returned by the SqlDataReader is to iterate through each row with a while loop. The following code shows how to accomplish this:</p>
<pre> <span style="color:blue;">while</span> (rdr.Read())
{
<span style="color:green;">// get the results of each column</span>
<span style="color:blue;">string</span> contact = (<span style="color:blue;">string</span>)rdr["ContactName"];
<span style="color:blue;">string</span> company = (<span style="color:blue;">string</span>)rdr["CompanyName"];
<span style="color:blue;">string</span> city    = (<span style="color:blue;">string</span>)rdr["City"];

<span style="color:green;">// print out the results</span>
Console.Write("{0,-25}", contact);
Console.Write("{0,-20}", city);
Console.Write("{0,-25}", company);
Console.WriteLine();
}</pre>
<p>Notice the call to <em>Read</em> on the SqlDataReader, <em>rdr</em>, in the <em>while</em> loop condition in the code above.  The return value of <em>Read</em> is type bool and returns true as long as there are more records to read. After the last record in the data stream has been read, <em>Read</em> returns         false.</p>
<p>In previous lessons, we extracted the first column from the row by using the         SqlDataReader indexer, i.e. <em>rdr[0]</em>. You can extract each column of the row with a numeric indexer like this, but it isn&#8217;t very readable. The example above uses a string indexer, where the string is the column name from the SQL query (the table column name if you used an asterisk, *. String indexers are much more readable, making the code easier to maintain.</p>
<p>Regardless of the type of the indexer parameter, a SqlDataReader indexer will return type object. This is why the example above casts results to a string. Once the values are extracted, you can do whatever you want with them, such as printing them to output with Console type methods.</p>
<h4>Finishing Up</h4>
<p>Always remember to close your SqlDataReader, just like you need to close the SqlConnection. Wrap the data access code in a try block and put the close operation in the finally block, like this:</p>
<pre> <span style="color:blue;">try</span>
{
<span style="color:green;">// data access code</span>
}
<span style="color:blue;">finally</span>
{
<span style="color:green;">// 3. close the reader</span>
<span style="color:blue;">if</span> (rdr != <span style="color:blue;">null</span>)
{
rdr.Close();
}

<span style="color:green;">// close the connection too</span>
}</pre>
<p>The code above checks the SqlDataReader to make sure it isn&#8217;t null. After the code knows that a good instance of the SqlDataReader exists, it can close it. Listing 1 shows the code for the previous sections in its entirety.</p>
<h5>Listing 1: Using the SqlDataReader</h5>
<pre><span style="color:blue;">using</span> System;
<span style="color:blue;">using</span> System.Data;
<span style="color:blue;">using</span> System.Data.SqlClient;

<span style="color:blue;">namespace</span> Lesson04
{
<span style="color:blue;">class</span> ReaderDemo
{
<span style="color:blue;">static</span> <span style="color:blue;">void</span> Main()
{
ReaderDemo rd = <span style="color:blue;">new</span> ReaderDemo();
rd.SimpleRead();
}

<span style="color:blue;">public</span> <span style="color:blue;">void</span> SimpleRead()
{
<span style="color:green;">// declare the SqlDataReader, which is used in</span>
<span style="color:green;">// both the try block and the finally block</span>
SqlDataReader rdr = <span style="color:blue;">null</span>;

<span style="color:green;">// create a connection object</span>
SqlConnection conn = <span style="color:blue;">new</span> SqlConnection(
"Data Source=(local);Initial Catalog=Northwind;Integrated Security=SSPI");

<span style="color:green;">// create a command object</span>
SqlCommand cmd  = <span style="color:blue;">new</span> SqlCommand(
"select * from Customers", conn);

<span style="color:blue;">try</span>
{
<span style="color:green;">// open the connection</span>
conn.Open();

<span style="color:green;">// 1.  get an instance of the SqlDataReader</span>
rdr = cmd.ExecuteReader();

<span style="color:green;">// print a set of column headers</span>
Console.WriteLine(
"Contact Name             City                Company Name");
Console.WriteLine(
"------------             ------------        ------------");

<span style="color:green;">// 2.  print necessary columns of each record</span>
<span style="color:blue;">while</span> (rdr.Read())
{
<span style="color:green;">// get the results of each column</span>
<span style="color:blue;">string</span> contact = (<span style="color:blue;">string</span>)rdr["ContactName"];
<span style="color:blue;">string</span> company = (<span style="color:blue;">string</span>)rdr["CompanyName"];
<span style="color:blue;">string</span> city    = (<span style="color:blue;">string</span>)rdr["City"];

<span style="color:green;">// print out the results</span>
Console.Write("{0,-25}", contact);
Console.Write("{0,-20}", city);
Console.Write("{0,-25}", company);
Console.WriteLine();
}
}
<span style="color:blue;">finally</span>
{
<span style="color:green;">// 3. close the reader</span>
<span style="color:blue;">if</span> (rdr != <span style="color:blue;">null</span>)
{
rdr.Close();
}

<span style="color:green;">// close the connection</span>
<span style="color:blue;">if</span> (conn != <span style="color:blue;">null</span>)
{
conn.Close();
}
}
}
}
}</pre>
<h4>Summary</h4>
<p>SqlDataReader objects allow you to read data in a fast forward-only manner. You obtain data by reading each row from the data stream. Call the Close method of the SqlDataReader to ensure there are not any resource leaks.</p>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/dotnetsourcecode.wordpress.com/8/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/dotnetsourcecode.wordpress.com/8/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/dotnetsourcecode.wordpress.com/8/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/dotnetsourcecode.wordpress.com/8/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/dotnetsourcecode.wordpress.com/8/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/dotnetsourcecode.wordpress.com/8/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/dotnetsourcecode.wordpress.com/8/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/dotnetsourcecode.wordpress.com/8/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/dotnetsourcecode.wordpress.com/8/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/dotnetsourcecode.wordpress.com/8/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/dotnetsourcecode.wordpress.com/8/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/dotnetsourcecode.wordpress.com/8/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/dotnetsourcecode.wordpress.com/8/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/dotnetsourcecode.wordpress.com/8/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/dotnetsourcecode.wordpress.com/8/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/dotnetsourcecode.wordpress.com/8/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetsourcecode.wordpress.com&amp;blog=3513798&amp;post=8&amp;subd=dotnetsourcecode&amp;ref=&amp;feed=1" width="1" height="1" /><div class="sharedaddy"></div>]]></content:encoded>
			<wfw:commentRss>http://dotnetsourcecode.wordpress.com/2008/04/18/reading-data-with-the-sqldatareader/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/3016c9256318b7150baceec904d3723d?s=96&#38;d=identicon" medium="image">
			<media:title type="html">dotnetsourcecode</media:title>
		</media:content>
	</item>
		<item>
		<title>Working with Disconnected Data &#8211; The DataSet and SqlDataAdapter</title>
		<link>http://dotnetsourcecode.wordpress.com/2008/04/18/working-with-disconnected-data-the-dataset-and-sqldataadapter/</link>
		<comments>http://dotnetsourcecode.wordpress.com/2008/04/18/working-with-disconnected-data-the-dataset-and-sqldataadapter/#comments</comments>
		<pubDate>Fri, 18 Apr 2008 04:45:34 +0000</pubDate>
		<dc:creator>dotnetsourcecode</dc:creator>
				<category><![CDATA[ADO.Net]]></category>

		<guid isPermaLink="false">http://dotnetsourcecode.wordpress.com/?p=7</guid>
		<description><![CDATA[Working with Disconnected Data &#8211; The DataSet and SqlDataAdapter This lesson explains how to work with disconnected data, using the DataSet and SqlDataAdapter objects. Here are the objectives of this lesson: Understand the need for disconnected data. Obtain a basic understanding of what a DataSet is for. Learn to use a SqlDataAdapter to retrieve and [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetsourcecode.wordpress.com&amp;blog=3513798&amp;post=7&amp;subd=dotnetsourcecode&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<h4><strong><strong>Working with Disconnected Data &#8211; The DataSet and SqlDataAdapter</strong></strong></h4>
<p>This lesson explains how to work with disconnected data, using the DataSet and SqlDataAdapter objects. Here are the objectives of this lesson:</p>
<ul>
<li> Understand the need for disconnected data.</li>
<li> Obtain a basic understanding of what a DataSet is for.</li>
<li> Learn to use a SqlDataAdapter to retrieve and update data.</li>
</ul>
<h4>Introduction</h4>
<p>In Lesson 3, we discussed a fully connected mode of operation for interacting with a data source by using the SqlCommand object. In Lesson 4, we learned about how to read data quickly an let go of the connection with the SqlDataReader. This Lesson shows how to accomplish something in-between SqlConnection and SqlDataReader interaction by using the DataSet and SqlDataAdapter objects.</p>
<p>A DataSet is an in-memory data store that can hold numerous tables. DataSets only hold data and do not interact with a data source. It is the SqlDataAdapter that manages connections with the data source and gives us disconnected behavior. The SqlDataAdapter opens a connection only when required and closes it as soon as it has performed its task. For example, the SqlDataAdapter performs the following tasks when filling a DataSet with data:</p>
<ol>
<li> Open connection</li>
<li> Retrieve data into DataSet</li>
<li> Close connection</li>
</ol>
<p>and performs the following actions when updating data source with DataSet         changes:</p>
<ol>
<li> Open connection</li>
<li> Write changes from DataSet to data source</li>
<li> Close connection</li>
</ol>
<p>In between the Fill and Update operations, data source connections are closed and you are free to read and write data with the DataSet as you need. These are the mechanics of working with disconnected data. Because the applications holds on to connections only when necessary, the application becomes more scalable.</p>
<p>A couple scenarios illustrate why you would want to work with disconnected data: people working without network connectivity and making Web sites more scalable. Consider sales people who need customer data as they travel. At the beginning of the day, they&#8217;ll need to sync up with the main data base to have the latest information available. During the day, they&#8217;ll make modifications to existing customer data, add new customers, and input new orders. This is okay because they have a given region or customer base where other people won&#8217;t be changing the same records. At the end of the day, the sales person will connect to the network and update changes for overnight processing.</p>
<p>Another scenario is making a Web site more scalable. With a SqlDataReader, you have to go back to the data base for records every time you show a page. This requires a new connection for each page load, which will hurt scalability as the number of users increase. One way to relieve this is to use a DataSet that is updated one time and stored in cache. Every request for the page checks the cache and loads the data if it isn&#8217;t there or just pulls the data out of cache and displays it. This avoids a trip to the data base, making your application more efficient.</p>
<p>Exceptions to the scenario above include situations where you need to update data. You then have to make a decision, based on the nature of how the data will be used as to your strategy. Use disconnected data when your information is primarily read only, but consider other alternatives (such as using SqlCommand object for immediate update) when your requirements call for something more dynamic. Also, if the amount of data is so large that holding it in memory is impractical, you will need to use SqlDataReader for read-only data. Really, one could come up with all kinds of exceptions, but the true guiding force should be the requirements of your application which will influence what your design should be.</p>
<h4>Creating a DataSet Object</h4>
<p>There isn&#8217;t anything special about instantiating a DataSet.  You just         create a new instance, just like any other object:</p>
<p><span style="font-size:85%;">DataSet dsCustomers = <span style="color:blue;">new</span> DataSet();</span></p>
<p>The DataSet constructor doesn&#8217;t require parameters. However there is one overload that accepts a string for the name of the DataSet, which is used if you were to serialize the data to XML. Since that isn&#8217;t a requirement for this example, I left it out. Right now, the DataSet is empty and you need a SqlDataAdapter to load it.</p>
<h4>Creating A SqlDataAdapter</h4>
<p>The SqlDataAdapter holds the SQL commands and connection object for reading and writing data. You initialize it with a SQL select statement and connection object:</p>
<p><span style="font-size:85%;">SqlDataAdapter daCustomers = <span style="color:blue;"> new</span> SqlDataAdapter(<br />
&#8220;select CustomerID, CompanyName from Customers&#8221;, conn); </span></p>
<p>The code above creates a new SqlDataAdapter, <em>daCustomers</em>.  The SQL         select statement specifies what data will be read into a DataSet.  The         connection object, <em>conn</em>, should have already been instantiated, but not opened. It is the SqlDataAdapter&#8217;s responsibility to open and close the connection during Fill and Update method calls.</p>
<p>As indicated earlier, the SqlDataAdapter contains all of the commands necessary to interact with the data source. The code showed how to specify the select statment, but didn&#8217;t show the insert, update, and delete statements. These are added to the SqlDataAdapter after it is instantiated.</p>
<p>There are two ways to add insert, update, and delete commands: via SqlDataAdapter properties or with a SqlCommandBuilder. In this lesson, I&#8217;m going to show you the easy way of doing it with the SqlCommandBuilder. In a later lesson, I&#8217;ll show you how to use the SqlDataAdapter properties, which takes more work but will give you more capabilities than what the SqlCommandBuilder does. Here&#8217;s how to add commands to the SqlDataAdapter with the SqlCommandBuilder:</p>
<p><span style="font-size:85%;">SqlCommandBuilder cmdBldr = <span style="color:blue;"> new</span> SqlCommandBuilder(daCustomers); </span></p>
<p>Notice in the code above that the SqlCommandBuilder is instantiated with a single constructor parameter of the SqlDataAdapter, <em>daCustomers</em>, instance. This tells the SqlCommandBuilder what SqlDataAdapter to add commands to. The SqlCommandBuilder will read the SQL select statement (specified when the SqlDataAdapter was instantiated), infer the insert, update, and delete commands, and assign the new commands to the Insert, Update, and Delete properties of the SqlDataAdapter, respectively.</p>
<p>As I mentioned earlier, the SqlCommandBuilder has limitations. It works when you do a simple select statement on a single table. However, when you need a join of two or mor tables or must do a stored procedure, it won&#8217;t work. I&#8217;ll describe a work-around for these scenarios in future lessons.</p>
<h4>Filling the DataSet</h4>
<p>Once you have a DataSet and SqlDataAdapter instances, you need to fill the DataSet. Here&#8217;s how to do it, by using the Fill method of the SqlDataAdapter:</p>
<p><span style="font-size:85%;">daCustomers.Fill(dsCustomers, &#8220;Customers&#8221;); </span></p>
<p>The <em>Fill</em> method, in the code above, takes two parameters: a DataSet and a table name. The DataSet must be instantiated before trying to fill it with data. The second parameter is the name of the table that will be created in the DataSet. You can name the table anything you want. Its purpose is so you can identify the table with a meaningful name later on. Typically, I&#8217;ll give it the same name as the database table. However, if the SqlDataAdapter&#8217;s select command contains a join, you&#8217;ll need to find another meaningful name.</p>
<p>The <em>Fill</em> method has an overload that accepts one parameter for the DataSet only. In that case, the table created has a default name of &#8220;table1&#8243; for the first table. The number will be incremented (table2, table3, &#8230;, tableN) for each table added to the DataSet where the table name was not specified in the Fill method.</p>
<h4>Using the DataSet</h4>
<p>A DataSet will bind with both ASP.NET and Windows forms DataGrids. Here&#8217;s an example that assigns the DataSet to a Windows forms DataGrid:</p>
<p><span style="font-size:85%;">dgCustomers.DataSource = dsCustomers;<br />
dgCustomers.DataMember = &#8220;Customers&#8221;; </span></p>
<p>The first thing we do, in the code above, is assign the DataSet to the DataSource property of the DataGrid. This lets the DataGrid know that it has something to bind to, but you will get a &#8216;+&#8217; sign in the GUI because the DataSet can hold multiple tables and this would allow you to expand each available table. To specify exactly which table to use, set the DataGrid&#8217;s <em>DataMember</em> property to the name of the table.  In the         example, we set the name to <em>Customers</em>, which is the same name used as the second parameter to the SqlDataAdapter Fill method. This is why I like to give the table a name in the <em>Fill</em> method, as it makes         subsequent code more readable.</p>
<h4>Updating Changes</h4>
<p>After modifications are made to the data, you&#8217;ll want to write the changes back to the data base. Refer to previous discussion in the Introduction of this article on update guidance. The following code shows how to use the <em>Update</em> method of the SqlDataAdapter to push modifications back to the data base.</p>
<p><span style="font-size:85%;">daCustomers.Update(dsCustomers, &#8220;Customers&#8221;); </span></p>
<p>The <em>Update</em> method, above, is called on the SqlDataAdapter instance that         originally filled the <em>dsCustomers</em> DataSet.  The second parameter         to the <em>Update</em> method specifies which table, from the DataSet, to update. The table contains a list of records that have been modified and the Insert, Update, and Delete properties of the SqlDataAdapter contain the SQL statements used to make data base modifications.</p>
<h4>Putting it All Together</h4>
<p>Until now, you&#8217;ve seen the pieces required to implement disconnected data managment. What you really need is to see all this implemented in an application. Listing 1 shows how the code from all the previous sections is used in a working program that has been simplified to enhance the points of this lesson:</p>
<h5>Listing 1: Implementing a Disconnected Data Management Strategy</h5>
<pre><span style="color:blue;">using</span> System;
<span style="color:blue;">using</span> System.Data;
<span style="color:blue;">using</span> System.Data.SqlClient;
<span style="color:blue;">using</span> System.Drawing;
<span style="color:blue;">using</span> System.Windows.forms;

<span style="color:blue;">class</span> DisconnectedDataform : form
{
<span style="color:blue;">private</span> SqlConnection  conn;
<span style="color:blue;">private</span> SqlDataAdapter daCustomers;

<span style="color:blue;">private</span> DataSet  dsCustomers;
<span style="color:blue;">private</span> DataGrid dgCustomers;

<span style="color:blue;">private</span> <span style="color:blue;">const</span> <span style="color:blue;">string</span> tableName = "Customers";

<span style="color:green;">// initialize form with DataGrid and Button</span>
<span style="color:blue;">public</span> DisconnectedDataform()
{
<span style="color:green;">// fill dataset</span>
Initdata();

<span style="color:green;">// set up datagrid</span>
dgCustomers = <span style="color:blue;">new</span> DataGrid();
dgCustomers.Location = <span style="color:blue;">new</span> Point(5, 5);
dgCustomers.Size = <span style="color:blue;">new</span> Size(
<span style="color:blue;">this</span>.Clientrectangle.Size.Width - 10,
<span style="color:blue;">this</span>.Clientrectangle.Height - 50);
dgCustomers.DataSource = dsCustomers;
dgCustomers.DataMember = tableName;

<span style="color:green;">// create update button</span>
Button btnUpdate = <span style="color:blue;">new</span> Button();
btnUpdate.Text = "Update";
btnUpdate.Location = <span style="color:blue;">new</span> Point(
<span style="color:blue;">this</span>.Clientrectangle.Width/2 - btnUpdate.Width/2,
<span style="color:blue;">this</span>.Clientrectangle.Height - (btnUpdate.Height + 10));
btnUpdate.Click += <span style="color:blue;">new</span> EventHandler(btnUpdateClicked);

<span style="color:green;">// make sure controls appear on form</span>
Controls.AddRange(<span style="color:blue;">new</span> Control[] { dgCustomers, btnUpdate });
}

<span style="color:green;">// set up ADO.NET objects</span>
<span style="color:blue;">public</span> <span style="color:blue;">void</span> Initdata()
{
<span style="color:green;">// instantiate the connection</span>
conn = <span style="color:blue;">new</span> SqlConnection(
"Server=(local);DataBase=Northwind;Integrated Security=SSPI");

<span style="color:green;">// 1. instantiate a new DataSet</span>
dsCustomers = <span style="color:blue;">new</span> DataSet();

<span style="color:green;">// 2. init SqlDataAdapter with select command and connection</span>
daCustomers = <span style="color:blue;">new</span> SqlDataAdapter(
"select CustomerID, CompanyName from Customers", conn);

<span style="color:green;">// 3. fill in insert, update, and delete commands</span>
SqlCommandBuilder cmdBldr = <span style="color:blue;">new</span> SqlCommandBuilder(daCustomers);

<span style="color:green;">// 4. fill the dataset</span>
daCustomers.Fill(dsCustomers, tableName);
}

<span style="color:green;">// Update button was clicked</span>
<span style="color:blue;">public</span> <span style="color:blue;">void</span> btnUpdateClicked(<span style="color:blue;">object</span> sender, EventArgs e)
{
<span style="color:green;">// write changes back to DataBase</span>
daCustomers.Update(dsCustomers, tableName);
}

<span style="color:green;">// start the Windows form</span>
<span style="color:blue;">static</span> <span style="color:blue;">void</span> Main()
{
Application.Run(<span style="color:blue;">new</span> DisconnectedDataform());
}
}</pre>
<p>The <em>Initdata</em> method in Listing 1 contains the methods necessary to set up the SqlDataAdapter and DataSet. Notice that various data objects are defined at class level so they can be used in multiple methods. The DataGrid&#8217;s <em>DataSource</em> property is set in the constructor.          Whenever a user clicks the Update button, the <em>Update</em> method in the <em>btnUpdateClicked</em> event handler is called, pushing modifications back to the data base.</p>
<h4>Summary</h4>
<p>DataSets hold multiple tables and can be kept in memory and reused. The SqlDataAdapter enables you to fill a DataSet and Update changes back to the data base. You don&#8217;t have to worry about opening and closing the SqlConnection because the SqlDataAdapter does it automatically. A SqlCommandBuilder populates insert, update, and delete commands based on the SqlDataAdapter&#8217;s select statement. Use the <em>Fill</em> method of the         SqlDataAdapter to fill a DataSet with data.  Call the SqlDataAdapter&#8217;s <em>Update</em> method to push changes back to a data base.</p>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/dotnetsourcecode.wordpress.com/7/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/dotnetsourcecode.wordpress.com/7/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/dotnetsourcecode.wordpress.com/7/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/dotnetsourcecode.wordpress.com/7/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/dotnetsourcecode.wordpress.com/7/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/dotnetsourcecode.wordpress.com/7/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/dotnetsourcecode.wordpress.com/7/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/dotnetsourcecode.wordpress.com/7/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/dotnetsourcecode.wordpress.com/7/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/dotnetsourcecode.wordpress.com/7/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/dotnetsourcecode.wordpress.com/7/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/dotnetsourcecode.wordpress.com/7/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/dotnetsourcecode.wordpress.com/7/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/dotnetsourcecode.wordpress.com/7/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/dotnetsourcecode.wordpress.com/7/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/dotnetsourcecode.wordpress.com/7/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetsourcecode.wordpress.com&amp;blog=3513798&amp;post=7&amp;subd=dotnetsourcecode&amp;ref=&amp;feed=1" width="1" height="1" /><div class="sharedaddy"></div>]]></content:encoded>
			<wfw:commentRss>http://dotnetsourcecode.wordpress.com/2008/04/18/working-with-disconnected-data-the-dataset-and-sqldataadapter/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/3016c9256318b7150baceec904d3723d?s=96&#38;d=identicon" medium="image">
			<media:title type="html">dotnetsourcecode</media:title>
		</media:content>
	</item>
		<item>
		<title>Adding Parameters to Commands</title>
		<link>http://dotnetsourcecode.wordpress.com/2008/04/18/adding-parameters-to-commands/</link>
		<comments>http://dotnetsourcecode.wordpress.com/2008/04/18/adding-parameters-to-commands/#comments</comments>
		<pubDate>Fri, 18 Apr 2008 04:44:40 +0000</pubDate>
		<dc:creator>dotnetsourcecode</dc:creator>
				<category><![CDATA[ADO.Net]]></category>

		<guid isPermaLink="false">http://dotnetsourcecode.wordpress.com/?p=6</guid>
		<description><![CDATA[Adding Parameters to Commands This lesson shows you how to use parameters in your commands. Here are the objectives of this lesson: Understand what a parameter is. Be informed about the benefits of using parameters. Learn how to create a parameter. Learn how to assign parameters to commands. Introduction When working with data, you&#8217;ll often [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetsourcecode.wordpress.com&amp;blog=3513798&amp;post=6&amp;subd=dotnetsourcecode&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<h4>Adding Parameters to Commands</h4>
<p>This lesson shows you how to use parameters in your commands.  Here are the         objectives of this lesson:</p>
<ul>
<li> Understand what a parameter is.</li>
<li> Be informed about the benefits of using parameters.</li>
<li> Learn how to create a parameter.</li>
<li> Learn how to assign parameters to commands.</li>
</ul>
<h4>Introduction</h4>
<p>When working with data, you&#8217;ll often want to filter results based on some criteria. Typically, this is done by accepting input from a user and using that input to form a SQL query. For example, a sales person may need to see all orders between specific dates. Another query might be to filter customers by city.</p>
<p>As you know, the SQL query assigned to a SqlCommand object is simply a string. So, if you want to filter a query, you could build the string dynamically, but you wouldn&#8217;t want to. Here is a bad example of filtering a query.</p>
<pre> <span style="color:green;">// don't ever do this!</span>
SqlCommand cmd = <span style="color:blue;">new</span> SqlCommand(
"select * from Customers where city = '" + inputCity + "'";</pre>
<p>Don&#8217;t ever build a query this way!  The input variable, <em>inputCity</em>, is typically retrieved from a TextBox control on either a Windows form or a Web Page. Anything placed into that TextBox control will be put into <em>inputCity</em> and added to your SQL string. This situation invites a hacker to replace that string with something malicious. In the worst case, you could give full control of your computer away.</p>
<p>Instead of dynamically building a string, as shown in the bad example above, use parameters. Anything placed into a parameter will be treated as field data, not part of the SQL statement, which makes your application much more secure.</p>
<p>Using parameterized queries is a three step process:</p>
<ol>
<li> Construct the SqlCommand command string with parameters.</li>
<li> Declare a SqlParameter object, assigning values as appropriate.</li>
<li> Assign the SqlParameter object to the SqlCommand object&#8217;s Parameters property.</li>
</ol>
<p>The following sections take you step-by-step through this process.</p>
<h4>preparing a SqlCommand Object for Parameters</h4>
<p>The first step in using parameters in SQL queries is to build a command string containing parameter placeholders. These placeholders are filled in with actual parameter values when the SqlCommand executes. Proper syntax of a parameter is to use an &#8216;@&#8217; symbol prefix on the parameter name as shown below:</p>
<pre> <span style="color:green;">// 1. declare command object with parameter</span>
SqlCommand cmd = <span style="color:blue;">new</span> SqlCommand(
"select * from Customers where city = @City", conn);</pre>
<p>In the SqlCommand constructor above, the first argument contains a         parameter declaration, <em>@City</em>. This example used one parameter, but you can have as many parameters as needed to customize the query. Each parameter will match a SqlParameter object that must be assigned to this SqlCommand object.</p>
<h4>Declaring a SqlParameter Object</h4>
<p>Each parameter in a SQL statement must be defined. This is the purpose of the SqlParameter type. Your code must define a SqlParameter instance for each parameter in a SqlCommand object&#8217;s SQL command. The following code defines a parameter for the <em>@City</em> parameter from the previous section:</p>
<pre> <span style="color:green;">// 2. define parameters used in command object</span>
SqlParameter param  = <span style="color:blue;">new</span> SqlParameter();
param.ParameterName = "@City";
param.Value         = inputCity;</pre>
<p>Notice that the ParameterName property of the SqlParameter instance must be spelled exactly as the parameter that is used in the SqlCommand SQL command string. You must also specify a value for the command. When the SqlCommand object executes, the parameter will be replaced with this value.</p>
<h4>Associate a SqlParameter Object with a SqlCommand Object</h4>
<p>For each parameter defined in the SQL command string argument to a SqlCommand object, you must define a SqlParameter. You must also let the SqlCommand object know about the SqlParameter by assigning the SqlParameter instance to the Parameters property of the SqlCommand object. The following code shows how to do this:</p>
<pre> <span style="color:green;">// 3. add new parameter to command object</span>
cmd.Parameters.Add(param);</pre>
<p>The SqlParameter instance is the argument to the Add method of the Parameters property for the SqlCommand object above. You must add a unique SqlParameter for each parameter defined in the SqlCommand object&#8217;s SQL command string.</p>
<h4>Putting it All Together</h4>
<p>You already know how to use SqlCommand and SqlDataReader objects. The following code demonstrates a working program that uses SqlParameter objects. So, everything should be familiar by now, except for the new parts presented in this article:</p>
<h5>Listing 1: Adding Parameters to Queries</h5>
<pre><span style="color:blue;">using</span> System;
<span style="color:blue;">using</span> System.Data;
<span style="color:blue;">using</span> System.Data.SqlClient;

<span style="color:blue;">class</span> ParamDemo
{
<span style="color:blue;">static</span> <span style="color:blue;">void</span> Main()
{
<span style="color:green;">// conn and reader declared outside try</span>
<span style="color:green;">// block for visibility in finally block</span>
SqlConnection conn   = <span style="color:blue;">null</span>;
SqlDataReader reader = <span style="color:blue;">null</span>;

<span style="color:blue;">string</span> inputCity = "London";

<span style="color:blue;">try</span>
{
<span style="color:green;">// instantiate and open connection</span>
conn =  <span style="color:blue;">new</span>
SqlConnection("Server=(local);DataBase=Northwind;Integrated Security=SSPI");
conn.Open();

<span style="color:green;">// don't ever do this!</span>
<span style="color:green;">//   SqlCommand cmd = new SqlCommand(</span>
<span style="color:green;">//    "select * from Customers where city = '" + inputCity + "'";</span>

<span style="color:green;">// 1. declare command object with parameter</span>
SqlCommand cmd = <span style="color:blue;">new</span> SqlCommand(
"select * from Customers where city = @City", conn);

<span style="color:green;">// 2. define parameters used in command object</span>
SqlParameter param  = <span style="color:blue;">new</span> SqlParameter();
param.ParameterName = "@City";
param.Value         = inputCity;

<span style="color:green;">// 3. add new parameter to command object</span>
cmd.Parameters.Add(param);

<span style="color:green;">// get data stream</span>
reader = cmd.ExecuteReader();

<span style="color:green;">// write each record</span>
<span style="color:blue;">while</span>(reader.Read())
{
Console.WriteLine("{0}, {1}",
reader["CompanyName"],
reader["ContactName"]);
}
}
<span style="color:blue;">finally</span>
{
<span style="color:green;">// close reader</span>
<span style="color:blue;">if</span> (reader != <span style="color:blue;">null</span>)
{
reader.Close();
}

<span style="color:green;">// close connection</span>
<span style="color:blue;">if</span> (conn != <span style="color:blue;">null</span>)
{
conn.Close();
}
}
}
}</pre>
<p>The code in Listing 1 simply retrieves records for each customer that lives in London. This was made more secure through the use of parameters. Besides using parameters, all of the other code contains techniques you&#8217;ve learned in previous lessons.</p>
<h4>Summary</h4>
<p>You should use parameters to filter queries in a secure manner. The process of using parameter contains three steps: define the parameter in the SqlCommand command string, declare the SqlParameter object with applicable properties, and assign the SqlParameter object to the SqlCommand object. When the SqlCommand executes, parameters will be replaced with values specified by the SqlParameter object.</p>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/dotnetsourcecode.wordpress.com/6/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/dotnetsourcecode.wordpress.com/6/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/dotnetsourcecode.wordpress.com/6/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/dotnetsourcecode.wordpress.com/6/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/dotnetsourcecode.wordpress.com/6/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/dotnetsourcecode.wordpress.com/6/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/dotnetsourcecode.wordpress.com/6/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/dotnetsourcecode.wordpress.com/6/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/dotnetsourcecode.wordpress.com/6/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/dotnetsourcecode.wordpress.com/6/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/dotnetsourcecode.wordpress.com/6/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/dotnetsourcecode.wordpress.com/6/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/dotnetsourcecode.wordpress.com/6/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/dotnetsourcecode.wordpress.com/6/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/dotnetsourcecode.wordpress.com/6/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/dotnetsourcecode.wordpress.com/6/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dotnetsourcecode.wordpress.com&amp;blog=3513798&amp;post=6&amp;subd=dotnetsourcecode&amp;ref=&amp;feed=1" width="1" height="1" /><div class="sharedaddy"></div>]]></content:encoded>
			<wfw:commentRss>http://dotnetsourcecode.wordpress.com/2008/04/18/adding-parameters-to-commands/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/3016c9256318b7150baceec904d3723d?s=96&#38;d=identicon" medium="image">
			<media:title type="html">dotnetsourcecode</media:title>
		</media:content>
	</item>
	</channel>
</rss>
