C# - How to save SQL Query Results to variable in C# ( Scalar value returned by query)

Scenario: Download Script

You are working as C# developer, You are writing C# Program in which you need to execute SQL Query that returns you single value, you need to execute query and save the result into variable.

In below script we will run two queries and save results into integer type and string type variables.

I queried my Customer tale to get total count and Top 1 Name in below example.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Data.SqlClient;
using System.Data;


namespace TechBrothersIT.com_CSharp_Tutorial
{
    class Program
    {
        static void Main(string[] args)
        {

            string datetime = DateTime.Now.ToString("yyyyMMddHHmmss");
            string LogFolder = @"C:\Log\";
            try
            {

                //Create Connection to SQL Server
                SqlConnection SQLConnection = new SqlConnection();
                SQLConnection.ConnectionString = "Data Source = (local); Initial Catalog =TechBrothersIT; "
                   + "Integrated Security=true;";


                //Query for getting Count
                string QueryCnt = "select count(*) from dbo.Customer";
                //Query for getting Name ( Returns only single value)
                string QueryName = "select Top 1 Name  from dbo.Customer";



                //Execute Queries and save results into variables
                SqlCommand CmdCnt = SQLConnection.CreateCommand();
                CmdCnt.CommandText = QueryCnt;

                SqlCommand CmdName = SQLConnection.CreateCommand();
                CmdName.CommandText = QueryName;

                SQLConnection.Open();
                Int32 CustomerCnt = (Int32)CmdCnt.ExecuteScalar();
                string CustomerName = (string)CmdName.ExecuteScalar();
                SQLConnection.Close();

                //Show values from variables
                Console.WriteLine("CustomerName:" + CustomerName);
                Console.WriteLine("CustomerCount:" + CustomerCnt.ToString());
                Console.ReadLine();
            }
            catch (Exception exception)
            {
                // Create Log File for Errors
                using (StreamWriter sw = File.CreateText(LogFolder
                    + "\\" + "ErrorLog_" + datetime + ".log"))
                {
                    sw.WriteLine(exception.ToString());

                }

            }

        }
    }
}


Here is my output from above program.
How to save SQL Query output to Variables in C# ( Scalar value)


No comments:

Post a Comment