谁能帮助我关于connection.Open()和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;
}
}
}
}