简体   繁体   English

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

[英]Where / when to use connection.close()

Can anyone help me about the connection.Open() and close(). 任何人都可以帮我解决连接问题。打开()和关闭()。 I'm not very sure about when to close and open the connection. 我不确定何时关闭并打开连接。 The code that is giving me an error is added below. 下面添加了给我一个错误的代码。

If anyone who can give me a tip about this, I would appreciate it. 如果有人能给我一个关于此的提示,我将不胜感激。 Please feel free to edit my code showing where to close the connection in order for me to learn from it. 请随时编辑我的代码,显示关闭连接的位置,以便我从中学习。

I am still a student. 我还是个学生。 Thank you. 谢谢。 =) =)

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



    }
}
}

you don't have close the connection explicitly since you're having using {} block with sqlconnection object. 您没有显式关闭连接,因为您正在使用带有sqlconnection对象的{}块。 The connection will automatically get closed. 连接将自动关闭。

second if you want to close the connection explicitly then close it once all your db operations are finished. 第二,如果要显式关闭连接,则在完成所有数据库操作后关闭它。

for eg close it when your adapter fill operation is finished. 例如,当适配器填充操作完成时关闭它。

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

This section: 这个部分:

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

You are re-using the same connection after closing it. 关闭后,您将重新使用相同的连接。 Re-open and re-use. 重新打开并重复使用。 Or don't close at all as you are still in the same using block. 或者根本不关闭,因为你仍然using相同的块。

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

The Fill method implicitly opens the Connection that the DataAdapter is using if it finds that the connection is not already open. 如果发现连接尚未打开,则Fill方法隐式打开DataAdapter正在使用的Connection。 If Fill opened the connection, it will also close the connection when Fill is finished. 如果Fill打开连接,它也将在Fill完成时关闭连接。

So, in the above section "conn.close()" shouldn't matter, "Fill" will open the connection and close it. 所以,在上面的章节“conn.close()”无关紧要,“填充”将打开连接并关闭它。

The using block will dispose off the connection once done with it. 一旦完成, using块将丢弃连接。 So, explicitly closing a connection is not required. 因此,不需要显式关闭连接。

Sql dataAdapter itself manages connection .it opens and closes after fill command , However using ExecuteReader or ExecuteNonQuery explicitly requires connection to open and close, you can open conection just before executing nonquery and executereader command , How ever one more scenario could be if your code faces an error and code does not reach to conn.close(); Sql dataAdapter本身管理连接.it在fill命令之后打开和关闭。但是使用ExecuteReader或ExecuteNonQuery显然需要连接打开和关闭,你可以在执行nonquery和executereader命令之前打开连接,如果你的代码面临的话还有一个场景。错误和代码无法到达conn.close(); command . 命令。

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



    }
}
}

Your connection string needs to have "MultipleActiveResultSets=True" added to it.If you are using multiple command like you are having two commands in a single connection ,Either enable "MultipleActiveResultSets=True" in your connection string or ,Open and close after every transaction with server (Single command per connection). 您的连接字符串需要添加“MultipleActiveResultSets = True”。如果您使用多个命令,就像在一个连接中有两个命令一样,请在连接字符串中启用“MultipleActiveResultSets = True”,或者在每次连接后打开并关闭与服务器的事务(每个连接一个命令)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 EF使用和BeginTransaction,何时调用Connection.Close()? - EF using and BeginTransaction, when to call Connection.Close()? “connection.Close()”是关闭SQL连接的最佳或最安全的方法吗? - Is “connection.Close()” the best or safest way to close an SQL connection? 为什么 Oledb Connection.Close() 执行时间太长? - Why does Oledb Connection.Close() take far too long to execute? 进程sqlservr.exe在C#中的Connection.Close()之后保持运行 - Process sqlservr.exe keeps running after Connection.Close() in C# SQL可能正在泄漏连接,即使我正在调用Connection.Close() - SQL probably leaking connections even though I'm calling Connection.Close() 使用时需要关闭连接吗? - Do I need to Close Connection when i use using? 当应用程序关闭时,DB连接会立即关闭吗? - When application close, will DB connection close instantly? 使用交易时关闭连接 - Close connection when using a Transaction 当使用“ DbConnection”时,我应该使用“ using”还是try-catch-finally来使用DbConnection.close()关闭连接? - When using “DbConnection” should I use “using” or try-catch-finally to use DbConnection.close() to close the connection? 测试完成后关闭连接 - Close connection when testing is done
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM