ADO.Net-ExecuteScalar - DotNet and DataBase

Wednesday, 1 August 2018

ADO.Net-ExecuteScalar




The ExecuteScalar() in .NetFramework is a part of SqlCommand Object, it is using to retrieve a single(scalar) value from Database after the execution of the SQL Statement supplied. The ExecuteScalar() executes SQL statements as well as Stored Procedure and returned a scalar value on the first column of the first row in the returned ResultSet.
If the ResultSet gets more than one columns or rows, it will take only the value of the first column of the first row, and all other values will ignore. If the ResultSet is empty ExecuteScalar() will return a null reference.

While working with SQL commands like Count,Max,Min,Sum(Aggregate functions), ExecuteScalar() is more suitable.

Example:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Configuration;
namespace EmployeeTimeSheet
{
    public partial class InsertEmployees : Form
    {
        public InsertEmployees()
        {
            InitializeComponent();
        }       

        private void btnSelect_Click(object sender, EventArgs e)
        {
            SqlDataReader reader;
            string connection = System.Configuration.ConfigurationManager.ConnectionStrings["connection"].ConnectionString;
            SqlConnection con = new SqlConnection(connection);
            con.Open();
            SqlCommand cmd = new SqlCommand("SELECT Count(*) FROM EmployeeInfo", con);
            int Count = Convert.ToInt32(cmd.ExecuteScalar());
            MessageBox.Show(Count );
            con.Close();
        }
    }
}

No comments:

Post a Comment

x

Get Updates On

Discussion updates

Straight Into Your INBOX!

Enter your email address to subscribe to this website and receive notifications of new posts by email.