ADO.NET ExecuteScalar in OleDbCommand Object

The ExecuteScalar() method in the OleDbCommand Object is used to retrieve a single value from the database after executing an SQL statement or stored procedure. It is commonly used when you expect a result set with a single value, such as retrieving aggregated values using functions like Count(*) or Sum().

ExecuteScalar()

When ExecuteScalar() is called, it executes the SQL statement or stored procedure and returns the value found in the first column of the first row of the result set. If the result set contains multiple columns or rows, ExecuteScalar() will only consider the value in the first column of the first row and discard all other values. If the result set is empty, meaning there are no rows returned, ExecuteScalar() will return a Null reference.

One of the advantages of using ExecuteScalar() is that it uses fewer system resources compared to ExecuteReader(). Since ExecuteScalar() is designed to retrieve a single value, it does not need to load and traverse a full result set. This makes it more efficient when you only require a single value from the database.

ExecuteScalar() is especially useful when you need to retrieve aggregated values or when you expect a result set with a single value. It allows you to obtain that value directly, without the need to process a result set or navigate through multiple rows.

Full Source VB.NET
Imports System.Data.OleDb 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 OleDbConnection Dim cmd As OleDbCommand Dim sql As String connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;" sql = "Your SQL Statement Here like Select Count(*) from product" cnn = New OleDbConnection(connetionString) Try cnn.Open() cmd = New OleDbCommand(sql, cnn) Dim count As Int32 = Convert.ToInt32(cmd.ExecuteScalar()) cmd.Dispose() cnn.Close() MsgBox(" No of Rows " & count) Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class
connetionString = "Provider = Microsoft.Jet.OLEDB.4.0; Data Source = Your mdb filename;"

sql = "Your SQL Statement Here like Select Count(*) from product"

You have to replace the string with your realtime variables.