任何人都可以幫助我瞭解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;
}
}
}
}
爲什麼不添加'finally'塊並關閉每個方法後的連接。然後在每個方法的開始處重新打開連接。經驗法則:只要你需要Sqlserver的數據,你需要一個開放的連接。一個連接只能處理一個查詢,直到它關閉並重新打開。 – BudBrot
你有什麼異常? – Damith
你在哪裏打開'getAllLoanInfoDS()'中的連接? –