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.
<% @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=( 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 |