Thursday, June 18, 2015

C# ADO.NET SqlCommand - ExecuteScalar

The ExecuteScalar() in C# SqlCommand Object is using for retrieve a single value from Database after the execution of the SQL Statement. The ExecuteScalar() executes SQL statements as well as Stored Procedure and returned a scalar value on first column of first row in the returned Result Set.
 Command.ExecuteScalar();

The ExecuteNonQuery() performs Data Definition tasks as well as Data Manipulation tasks also. The Data Definition tasks like creating Stored Procedures ,Views etc. perform by the ExecuteNonQuery() . Also Data Manipulation tasks like Insert , Update , Delete etc. also perform by the ExecuteNonQuery() of SqlCommand Object.

If the Result Set contains more than one columns or rows , it will take only the value of first column of the first row, and 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.

The following C# example shows how to use the method ExecuteScalar() through SqlCommand Object.

using System;
using System.Windows.Forms;
using System.Data.SqlClient; 

namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string connetionString = null;
            SqlConnection cnn ;
            SqlCommand cmd ;
            string sql = null;

            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);
            try
            {
                cnn.Open();
                cmd = new SqlCommand(sql, cnn);
                Int32 count = Convert.ToInt32(cmd.ExecuteScalar());
                cmd.Dispose();
                cnn.Close();
                MessageBox.Show (" No. of Rows " + count);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Can not open connection ! ");
            }
        }
    }
}

If you are searching life partner. your searching end with kpmarriage.com. now kpmarriage.com offer free matrimonial website which offer free message, free chat, free view contact information. so register here : kpmarriage.com- Free matrimonial website