0

I am using the parameterized select query for querying the mysql database. And below is the c# code I am using

 public static void ValidateName(MySqlConnection conn,List<Employee> EmpList, string Grp)
{
    string selectQuery = "Select Name from Employee where Group = @Group  AND @Name in (FirstName, LastName);";
     using (MySqlCommand cmd = new MySqlCommand(selectQuery, conn))
        {
         for (int i = 0; i < EmpList.Count; i++)
          {
            cmd.Parameters.Add("@Group", MySqlDbType.VarChar).Value = Grp;
            cmd.Parameters.Add("@Name", MySqlDbType.VarChar).Value = EmpList[i].Name;
            var reader = cmd.ExecuteReader();
            List<string> lineList = new List<string>();
            while (reader.Read())
            {
                lineList.Add(reader.GetString(0));
            }
            if (lineList.Count <=0)
            {
               WriteValidationFailure(EmpList[i], "Failed");
            }
    }       
    }
  }

What is the benefit of using the cmd.Prepare(); does that improve my code in any ways. Also I need to know if I am having multiple functions like above in my program and everytime giving using (MySqlCommand cmd = new MySqlCommand(selectQuery, conn)) inside in the individual functions add any complexity to the code? I am new to creating database connection from the c# and not sure about how much complexity my code adds.

user4912134
  • 1,003
  • 5
  • 18
  • 47
  • where is cmd.Prepare(); in your code? – Akash KC Mar 14 '17 at 04:01
  • Possible duplicate of [How to correctly and efficiently reuse a prepared statement in C# .NET (SQL Server)?](http://stackoverflow.com/questions/20972375/how-to-correctly-and-efficiently-reuse-a-prepared-statement-in-c-sharp-net-sql) – Usman Mar 14 '17 at 04:03
  • @AkashKC I havent added the cmd.Prepare(); yet but checking if it would make any efficiency to my code – user4912134 Mar 14 '17 at 04:06
  • @Usman I have two questions. Can you please help me with this – user4912134 Mar 14 '17 at 04:12
  • Check out for pros and cons http://stackoverflow.com/questions/2449827/pros-and-cons-of-using-sqlcommand-prepare-in-c – vineeth Mar 14 '17 at 04:19

1 Answers1

0

Actually Prepare() method is most useful when you wanna execute a parametric StoredProcedure in database, When you call the Prepare(), ADO try to check parameter type and size with thing you provided already, It use full to avoid making database busy before your are not sure about procedure parameters. Give you gain in performance.

Mohammad Nikravesh
  • 947
  • 1
  • 8
  • 27