|
This method is used to retrieve single value from the database. Here the executeScalar() method is far efficient from the executeReader method. This method can be used in the queries where the function such as COUNT(*), MIN and MAX etc can be used.
Exzample of Execute Scalar:
Note:-This example will fetch the single value that is evaluating using count (*) aggregated function and display the value in the label.
ExecuteScalar.aspx
<% @ Page Language ="VB" AutoEventWireup ="false" CodeFile ="Example4.aspx.vb" Inherits ="Example4" %>
<! DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
< html xmlns ="http://www.w3.org/1999/xhtml" >
< head runat ="server">
</ head >
< body >
< form id ="form1" runat ="server">
< div >
< asp : Label ID ="Label1" runat ="server" Text ="Value Retrieve From Database" Width ="232px"></ asp : Label >
< asp : Label ID ="lblValue" runat ="server" Text ="Label" Width ="85px"></ asp : Label ></ div >
</ form >
</ body >
</ html >
ExecuteScalar.aspx.vb
Imports System
Imports System.Data
Imports System.Data.SqlClient
Partial Class Example4 Inherits System.Web.UI.Page
Protected Sub Page_Load( ByVal sender As Object , ByVal e As System.EventArgs) Handles Me .Load
Dim con As SqlConnection
Dim cmd As SqlCommand
con = New SqlConnection( "Data Source=localhost;Initial catalog=TestDB;UID=sa;pwd=sa" )
cmd = New SqlCommand()
cmd.Connection = con
cmd.CommandType = CommandType.Text
cmd.CommandText = "select count(*) from tblEmp"
con.Open()
lblValue.Text = cmd.ExecuteScalar
con.Close()
Response.Write( "Execute Scalar Fetch Values Successfully !!!" )
End Sub
End Class
|