何时/何时使用connection.close()

时间:2013-07-30 09:28:26

标签: c# asp.net

任何人都可以帮我解决连接问题。打开()和关闭()。我不确定何时关闭并打开连接。下面添加了给我一个错误的代码。

如果有人能给我一个关于此的提示,我将不胜感激。请随时编辑我的代码,显示关闭连接的位置,以便我从中学习。

我还是学生。谢谢。 =)

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;
        }



    }
}
}

3 个答案:

答案 0 :(得分: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;
                }

答案 1 :(得分: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的Connection   如果发现连接尚未打开,则使用。如果填写   打开连接,它也将在Fill时关闭连接   结束。

因此,在上面的章节中,“conn.close()”无关紧要,“填充”将打开连接并关闭它。

using块将在完成连接后将其释放。因此,不需要明确关闭连接。

答案 2 :(得分:0)

Sql dataAdapter本身管理连接.it在fill命令后打开和关闭。但是使用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 = True”。如果您使用多个命令,就像在一个连接中有两个命令一样,请在连接字符串中启用“MultipleActiveResultSets = True”或,每次与服务器进行交易后打开和关闭(每个连接一个命令)。