Retrieving a Single Value from the Database

for RuBoard

Sometimes, you only need to retrieve a single value from the database, instead of a record or set of records. In this case, though you could use the methods described earlier in this hour to retrieve the value, the Command object provides a better way. Instead of using the DataAdapter object to place the results into a DataSet , you can call the ExecuteScalar() method of the Command object directly. This returns just the single value that you've queried from the database.

The code in Listing 6.5 shows this method of retrieving a single value. There are only three major changes from the example in Listing 6.4. First, the database query uses the Count() SQL function to return a count of all the records in the Employees table. Second, rather than using a SqlDataAdapter to fill a DataSet , the ExecuteScalar() method of the Command object is used. Lastly, a label is used to display the output instead of a DataGrid . When the example in Listing 6.5 is loaded, it will look like Figure 6.3.

Figure 6.3. Binding the results of a database query to a DataGrid Web control.


Listing 6.6 Retrieving a Single Value from the Database Using ExecuteScalar()
 <% @Page Language="C#" %> <%@ Import Namespace="System.Data" %> <%@ Import Namespace="System.Data.SqlClient" %> <HTML> <HEAD>     <LINK rel="stylesheet" type="text/css" href="Main.css">     <!-- End Style Sheet -->     <script language="C#" runat="server" >       void Page_Load(Object Source, EventArgs E)       {          int recordCount;          SqlConnection conn = new SqlConnection("Initial Catalog=Northwind;  Server=( graphics/ccc.gif local);UID=sa;PWD=;");          SqlCommand cmd = new SqlCommand("SELECT count(*) FROM Employees",  conn);          SqlDataAdapter adapt = new SqlDataAdapter(cmd);          DataSet dsEmployees = new DataSet();          conn.Open();          recordCount = (int)cmd.ExecuteScalar();          conn.Close();          result.Text = recordCount.ToString();       }     </script> </HEAD> <BODY> <h1>Retrieving a Single Value</h1> <hr> <form runat="server" id=form1 name=form1>    The number of employees in the employee table:<br>    <asp:Label id=result runat="server"></asp:Label> </form> <hr> </BODY> </HTML> 
for RuBoard

Sams Teach Yourself ADO. NET in 24 Hours
Sams Teach Yourself ADO.NET in 24 Hours
ISBN: 0672323834
EAN: 2147483647
Year: 2002
Pages: 237 © 2008-2017.
If you may any questions please contact us: