08.01.2015 Views

Beginning Web Development, Silverlight, and ASP.NET AJAX

Beginning Web Development, Silverlight, and ASP.NET AJAX

Beginning Web Development, Silverlight, and ASP.NET AJAX

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

CHAPTER 4 ■ DATA BINDING WITH <strong>ASP</strong>.<strong>NET</strong> 87<br />

of a table in your database. Executing this type of comm<strong>and</strong> will return all records stored<br />

in that table.<br />

So, for example, if you want to create a query that returns the street address for customers<br />

in the AdventureWorks address database who live at postal code 98011, you<br />

would use code like this:<br />

string connectionString =<br />

<strong>Web</strong>ConfigurationManager.ConnectionStrings["AW"].ConnectionString;<br />

SqlConnection sqlCon = new SqlConnection(connectionString);<br />

SqlComm<strong>and</strong> sqlComm = new SqlComm<strong>and</strong>();<br />

sqlComm.Connection = sqlCon;<br />

sqlComm.Comm<strong>and</strong>Type = Comm<strong>and</strong>Type.Text;<br />

sqlComm.Comm<strong>and</strong>Text =<br />

"SELECT AddressLine1 FROM Person.Address " +<br />

"WHERE (PostalCode = N'98011')";<br />

Executing the Comm<strong>and</strong><br />

Now that you have your comm<strong>and</strong>, you are going to want to execute it to do anything<br />

meaningful. There are four different methods for executing an ADO.<strong>NET</strong> comm<strong>and</strong>:<br />

ExecuteNonQuery: This is used to execute a query for which you do not want to return<br />

a result set. For example, if you are inserting, updating, or deleting records, you can<br />

use the comm<strong>and</strong>’s ExecuteNonQuery method. It will return an integer containing the<br />

number of records that were affected.<br />

ExecuteScalar: This executes the query <strong>and</strong> returns the first column of the first row<br />

of the result set. This is very useful for queries that use SQL COUNT or SUM, or other<br />

queries that return a desirable value.<br />

ExecuteReader: This executes a SELECT query <strong>and</strong> returns a DataReader object that can<br />

be used to provide forward-only read access to your data.<br />

ExecuteXmlReader: This is similar to ExecuteReader except that it gives you an XmlReader<br />

to access the data.<br />

So, executing a comm<strong>and</strong> to generate the required feedback is very straightforward.<br />

Here’s an example of executing the previous query, with the results available via a<br />

SqlDataReader:<br />

SqlDataReader sRead = sqlComm.ExecuteReader();

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!