ADO.NET ExecuteScalar in SqlCommand Object

ExecuteScalar() in SqlCommand Object is used for get a single value from Database after its execution. It executes SQL statements or Stored Procedure and returned a scalar value on first column of first row in the Result Set. If the Result Set contains more than one columns or rows , it takes only the first column of first row, all other values will ignore. If the Result Set is empty it will return a Null reference.

It is very useful to use with aggregate functions like Count(*) or Sum() etc. When compare to ExecuteReader() , ExecuteScalar() uses fewer System resources.

Imports System.Data.SqlClient
Public Class Form1
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim connetionString As String
        Dim cnn As SqlConnection
        Dim cmd As SqlCommand
        Dim sql As String

        connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password"
        sql = "Your SQL Statement Here like Select Count(*) from product"

        cnn = New SqlConnection(connetionString)
            cmd = New SqlCommand(sql, cnn)
            Dim count As Int32 = Convert.ToInt32(cmd.ExecuteScalar())
            MsgBox(" No. of Rows " & count)
        Catch ex As Exception
            MsgBox("Can not open connection ! ")
        End Try
    End Sub
End Class

connetionString = "Data Source = ServerName; Initial Catalog = DatabaseName; User ID = UserName; Password = Password"
sql = "Your SQL Statement Here like Select Count(*) from product"

You have to replace the string with your realtime variables. (C) 2021    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.
SiteMap  | Terms  | About