2017-03-13 46 views
-1

我有一個函數,它調用連接到mysql數據庫和查詢數據庫的不同函數。在這裏,我不確定如何重新使用我的conn and cmd以提高代碼效率。要將連接創建爲Validation()一次,並在我試圖連接到數據庫的任何地方將其重用到其他函數中。下面是我在做什麼重用連接並準備語句到mysql數據庫

private static void Validation(List<Employee> EmpList, string Group) 
    { 
     ValidateName(EmpList, Group); 
     ValidateDept(EmpList, Group); 
    } 
    public static void ValidateName(List<Employee> EmpList, string Grp) 
    { 
     var connStr = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString; 

     string selectQuery; 

     for (int i = 0; i < EmpList.Count; i++) 
     { 
      selectQuery = "Select Name from Employee where Group = @Group AND @Name in (FirstName, LastName);"; 
      using (MySqlConnection conn = new MySqlConnection(connStr)) 
      using (MySqlCommand cmd = new MySqlCommand(selectQuery, conn)) 
      { 
       cmd.Parameters.Add("@Group", MySqlDbType.VarChar).Value = Grp; 
       cmd.Parameters.Add("@Name", MySqlDbType.VarChar).Value = EmpList[i].Name; 
       conn.Open(); 
       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"); 
       } 
       conn.Close(); 
     }  
     } 
    } 

    public static void ValidateBreedingDept(List<Employee> EmpList, string Grp) 
    { 
     var connStr = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString; 

     string selectQuery; 

     for (int i = 0; i < EmpList.Count; i++) 
     { 
      selectQuery = "Select DepartmentName from Department where Group = @Group AND DepartmentName = @Dept;"; 
      using (MySqlConnection conn = new MySqlConnection(connStr)) 
      using (MySqlCommand cmd = new MySqlCommand(selectQuery, conn)) 
      { 
       cmd.Parameters.Add("@Group", MySqlDbType.VarChar).Value = Grp; 
       cmd.Parameters.Add("@Dept", MySqlDbType.VarChar).Value = EmpList[i].Dept; 
       conn.Open(); 
       var reader = cmd.ExecuteReader(); 
       List<string> lineList = new List<string>(); 
       while (reader.Read()) 
       { 
        lineList.Add(reader.GetString(0)); 
       } 
       if (lineList.Count <= 0) 
       { 
        WriteValidationFailure(listOfMouse[i], "Failed"); 
       } 
       conn.Close(); 
      } 
     } 
    } 

我是新來連接數據庫和從c#查詢。還有如何重寫查詢以使用Prepare語句。我知道我可以使用cmd.Prepare(),但是我可以將參數從一個函數重用到另一個函數。

回答

1

「重用我康恩和CMD,使效率更高的代碼」

你並不需要擔心。 C#通過使用稱爲連接池的東西來處理它。

全部「封閉」的連接並不真正關閉底層的連接,而是返回到供以後使用連接池,這正是你正在嘗試做的

Read more on MSDN