Check if value exist in database using C#

Sometimes we need to check whether a value exists in a particular column of database table or not. Below is the C# code for the same:

public static int checkExistingCustomerName(string custName)
{
     string strCmd = "SELECT COUNT(CustomerName) FROM CustomerDetails WHERE CustomerName='" + custName + "'";
     string custID;
     using (OleDbConnection conn = new OleDbConnection(Constants.connectionString))
     {
          try
          {
               OleDbCommand cmd = new OleDbCommand(strCmd, conn);
               conn.Open();
               object obj = cmd.ExecuteScalar();
               if (obj == DBNull.Value || Convert.ToInt32(obj)==0)
                    return 0;
               else
                    return 1;
           }
           catch (Exception ex)
           {
               return 1000;
           }
      }
}
Unknown's avatar

Author: Akanksha Gupta

I am a developer and working on SharePoint and Project Server in an MNC. I have more than 10 years of experience in the same field.

Leave a comment

Power Platform Academy

Start or Upgrade your Career with Power Platform

Learn with Akanksha

Python | Azure | AI/ML | OpenAI | MLOps

Design a site like this with WordPress.com
Get started