C# ADO.NET OleDbCommand - ExecuteScalar

The ExecuteScalar() in C# OleDbCommand Object uses to retrieve a single value from the Database after the execution of SQL Statements or Stored Procedures.

The ExecuteScalar() executes SQL statements or Stored Procedure and returned a scalar value on first column of first row in the returned Result Set. If the Result Set contains more than one columns or rows , it will return only the first column of the first row value and ignore all other values . 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 and also when compare to ExecuteReader() , ExecuteScalar() uses fewer System resources.

using System;
using System.Windows.Forms;
using System.Data.OleDb; 

namespace WindowsApplication1
    public partial class Form1 : Form
        public Form1()

        private void button1_Click(object sender, EventArgs e)
            string connetionString = null;
            OleDbConnection cnn ;
            OleDbCommand cmd ;
            string sql = null;

            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);
                cmd = new OleDbCommand(sql, cnn);
                Int32 count = Convert.ToInt32(cmd.ExecuteScalar());
                MessageBox.Show (" No of Rows " + count);
            catch (Exception ex)
                MessageBox.Show("Can not open connection ! ");
} (C) 2021    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.
SiteMap  | Terms  | About