2013-07-30 46 views
0

任何人都可以幫助我瞭解connection.Open()和close()。我不清楚何時關閉和打開連接。下面添加了給我一個錯誤的代碼。何處/何時使用connection.close()

如果有誰可以給​​我一個小費這個,我將不勝感激。請隨時編輯我的代碼,以顯示關閉連接的位置,以便我從中學習。

我還是個學生。謝謝。 =)

public class LoanDAL 
{ 
string connString = ConfigurationManager.ConnectionStrings["Oakhorizons"].ToString(); 
public LoanDAL() 
{ 
    // 
    // TODO: Add constructor logic here 
    // 
} 
public DataTable getAllLoanInfoDT() 
{ 
     using (SqlConnection conn = new SqlConnection(connString)) 
     { 
      SqlCommand cmd2 = new SqlCommand(); 
      cmd2.Connection = conn; 
      // cmd.CommandType = CommandType.StoredProcedure; 
      cmd2.CommandText = "SELECT DISTINCT loanUpdateDate FROM LoanPortfolio WHERE (custID LIKE 'OH00002') AND (loanType LIKE 'Personal Loan')"; 
      cmd2.Parameters.AddWithValue("@custID", "OH00002"); 
      cmd2.Parameters.AddWithValue("@loanType", "Personal Loan"); 
      conn.Open(); 
      DateTime loanUpdateDate = DateTime.Now; 
      SqlDataReader myReader = cmd2.ExecuteReader(); 
      while (myReader.Read()) 
      { 
       loanUpdateDate = Convert.ToDateTime(myReader[0]); 
       break; 
      } 

      DateTime currDateTime = DateTime.Now; 

      int loanToBeAdded = (((currDateTime.Year - loanUpdateDate.Year) * 12) + currDateTime.Month - loanUpdateDate.Month) * 500; 
      if (loanToBeAdded > 0) 
      { 
       String sql = "UPDATE LoanPortfolio SET loanPaid = loanPaid + " + loanToBeAdded.ToString() + ", LastUpdatedLoanPaidDate = " + DateTime.Now.ToString(); 
       sql += " WHERE (loanType LIKE 'Personal Loan') AND (custID LIKE 'OH00002')"; 
       cmd2.Connection = conn; 
       cmd2.CommandText = sql; 
       cmd2.ExecuteNonQuery(); 

      } 
      conn.Close(); 
      using (SqlDataAdapter dAd = new SqlDataAdapter("SELECT * FROM LoanPortfolio where custID like 'OH00002'", conn)) 
      { 
       DataTable dTable = new DataTable(); 
       dAd.Fill(dTable); 
       return dTable; 
      } 

     } 

} 

//Returning a DataSet which contains all the information in the Player Table 
public DataSet getAllLoanInfoDS() 
{ 
    using (SqlConnection conn = new SqlConnection(connString)) 
    { 

     using (SqlDataAdapter dAd = new SqlDataAdapter("SELECT * FROM LoanPortfolio where custID like 'OH00002", conn)) 
     { 
      DataSet myDS = new DataSet(); 
      dAd.Fill(myDS); 
      return myDS; 
     } 



    } 
} 
} 
+1

爲什麼不添加'finally'塊並關閉每個方法後的連接。然後在每個方法的開始處重新打開連接。經驗法則:只要你需要Sqlserver的數據,你需要一個開放的連接。一個連接只能處理一個查詢,直到它關閉並重新打開。 – BudBrot

+0

你有什麼異常? – Damith

+0

你在哪裏打開'getAllLoanInfoDS()'中的連接? –

回答

2

你沒有明確地接近,因爲你正在使用{}用的SqlConnection對象區塊具有連接。連接將自動關閉。

秒,如果你想明確關閉連接,然後關閉它,所有的數據庫操作完成後。

例如,在適配器填充操作完成後關閉它。

.... 
.... 
.... 
using (SqlDataAdapter dAd = new SqlDataAdapter("SELECT * FROM LoanPortfolio where custID like 'OH00002'", conn)) 
       { 
        DataTable dTable = new DataTable(); 
        dAd.Fill(dTable); 
        conn.Close(); 
        return dTable; 
       } 
+0

如果連接尚未打開然後.Fill()將打開它,使用它和關閉它但它不是一個限制,你可以明確地打開/關閉連接,當你做多個數據庫操作時,這將導致性能的提高 – vendettamit

0

本節:

conn.Close(); 
using (SqlDataAdapter dAd = new SqlDataAdapter("SELECT * FROM LoanPortfolio where custID like 'OH00002'", conn)) 
{ 
    DataTable dTable = new DataTable(); 
    dAd.Fill(dTable); 
    return dTable; 
} 

您要重新使用其關閉後對同一連接。重新打開並重新使用。或者根本不關閉,因爲您仍處於同一個using區塊。

更新:MSDN:http://msdn.microsoft.com/en-us/library/bh8kx08z(v=vs.100).aspx

Fill方法隱含打開一個DataAdapter的 如果發現連接尚未打開時使用的連接。如果Fill 已打開連接,則在填充爲 時,它也將關閉連接。

因此,在上面的部分「conn.close()」應該沒有關係,「填充」將打開連接並關閉它。

using塊將在處理完成後處置掉連接。所以,不需要明確關閉連接。

+0

那麼是什麼修復?或者你建議? – Damith

+0

我忽略了SqlAdapter 。更新的答案當然需要來自OP的更多信息,他究竟在哪裏得到例外 – Abhitalks

+0

他是我們爲EXECUTEReader和更新的單一連接也檢查他的代碼,你會看到他沒有釋放連接,讀者堅持連接對象。您可以在連接字符串中使用** MultipleActiveResultSets = True「**,以便您的連接允許多個命令,但是當使用MultipleActiveResultSets = True時,您必須考慮您正在使用哪個命令以及如何使用,考慮使用** MultipleActiveResultSets = True「**,但是在您的方法中,您正在更新和選擇數據,因此可能會得到錯誤的數據。 –

0

的Sql DataAdapter的自身管理連接。它打開和關閉填充命令後,但使用的ExecuteReader或明確的ExecuteNonQuery需要連接到打開和關閉,你可以執行nonquery和的ExecuteReader命令, 多一個場景如何過之前可以打開連接如如果你的代碼面臨錯誤,代碼沒有達到conn.close();命令。

public class LoanDAL 
{ 
string connString = ConfigurationManager.ConnectionStrings["Oakhorizons"].ToString(); 
public LoanDAL() 
{ 
    // 
    // TODO: Add constructor logic here 
    // 
} 
public DataTable getAllLoanInfoDT() 
{ 
     using (SqlConnection conn = new SqlConnection(connString)) 
     { 
      SqlCommand cmd2 = new SqlCommand(); 
      cmd2.Connection = conn; 
      // cmd.CommandType = CommandType.StoredProcedure; 
      cmd2.CommandText = "SELECT DISTINCT loanUpdateDate FROM LoanPortfolio WHERE (custID LIKE 'OH00002') AND (loanType LIKE 'Personal Loan')"; 
      cmd2.Parameters.AddWithValue("@custID", "OH00002"); 
      cmd2.Parameters.AddWithValue("@loanType", "Personal Loan"); 

      DateTime loanUpdateDate = DateTime.Now; 
      try 
      { 
      conn.Open(); 
      SqlDataReader myReader = cmd2.ExecuteReader(); 
      while (myReader.Read()) 
      { 
       loanUpdateDate = Convert.ToDateTime(myReader[0]); 
       break; 
      } 
       conn.Close(); 
      DateTime currDateTime = DateTime.Now; 
      } 
      Catch(Exception Ex) 
      {//Close connection in case of any exception . 
       conn.Close(); 
      } 
      int loanToBeAdded = (((currDateTime.Year - loanUpdateDate.Year) * 12) + currDateTime.Month - loanUpdateDate.Month) * 500; 
      if (loanToBeAdded > 0) 
      { 
       try 
       { 
       String sql = "UPDATE LoanPortfolio SET loanPaid = loanPaid + " + loanToBeAdded.ToString() + ", LastUpdatedLoanPaidDate = " + DateTime.Now.ToString(); 
       sql += " WHERE (loanType LIKE 'Personal Loan') AND (custID LIKE 'OH00002')"; 
       cmd2.Connection = conn; 
       cmd2.CommandText = sql; 
       conn.Open(); 
       cmd2.ExecuteNonQuery(); 
       conn.Close(); 
       } 
       Catch(Exception Ex) 
       { 
       //Close connection in case of exception . 
        Conn.close() 
        throw Ex; 
       } 
      }    
      using (SqlDataAdapter dAd = new SqlDataAdapter("SELECT * FROM LoanPortfolio where custID like 'OH00002'", conn)) 
      { 
       DataTable dTable = new DataTable(); 
       dAd.Fill(dTable); 
       return dTable; 
      } 

     } 

} 

//Returning a DataSet which contains all the information in the Player Table 
public DataSet getAllLoanInfoDS() 
{ 
    using (SqlConnection conn = new SqlConnection(connString)) 
    { 

     using (SqlDataAdapter dAd = new SqlDataAdapter("SELECT * FROM LoanPortfolio where custID like 'OH00002", conn)) 
     { 
      DataSet myDS = new DataSet(); 
      dAd.Fill(myDS); 
      return myDS; 
     } 



    } 
} 
} 

你的連接字符串需要有「MultipleActiveResultSets =真」添加到您正在使用多個命令就像你有一個單一的連接兩個命令吧。如果,可以啓用「MultipleActiveResultSets =真」在你的連接字符串或,每次與服務器進行事務後打開和關閉(每個連接有單個命令)。

相關問題