简体   繁体   English

什么是在C#中打开/关闭SqlConnection的最佳方法

[英]What is Best Approach for Opening/Closing SqlConnection in C#

I would like to know what could be best approach to open a SqlConnection with Sql Server 2008R2 Express Edition Database. 我想知道什么是用Sql Server 2008R2 Express Edition数据库打开SqlConnection最佳方法。 This Version of Sql has Limitations of RAM Usage and CPU Usage so we must adopt something best to open a SqlConnection . 此版本的Sql具有RAM使用率和CPU使用率的限制,因此我们必须采用最佳方法来打开SqlConnection

Right Now i am Checking Connection on Start and End of each and every Method. 现在,我正在检查每种方法的开始和结束处的连接。 Here is an example of that. 这是一个例子。

   private void CheckValidId(string Id)
    {
        CheckConnectionStatus();

        try
        {
            sqlConnection.Open();
            sqlCommand = new SqlCommand("select * from ValidId where id=@id", sqlConnection);
            sqlCommand.Parameters.AddWithValue("@id", Id);
            sqlDataReader = sqlCommand.ExecuteReader();
            While (sqlDataReader.Read())
            {
               string Test = sqlDataReader["Id"].toString();
               MessageBox.Show("Value of Id : " , Test);
            }
        }
        catch (Exception exp)
        {
            MessageBox.Show(exp.Message.ToString(), "Exception in CheckValidId");
        }
        finally
        {
            CheckConnectionStatus();
        }
    }

Here is CheckConnectionStatus Method 这是CheckConnectionStatus方法

    private void CheckConnectionStatus()
    {
        if (sqlConnection.State == ConnectionState.Open)
        {
            sqlConnection.Close();
        }
    }

What is best approach to perform this operation. 什么是执行此操作的最佳方法。

Thanks 谢谢

Just use using as it disposes of the connection once done. 完成后,只需使用using处理连接。

 using(SqlConnection conn = new SqlConnection("Connection string")){
  //do sql stuff
  conn.Open(); 
  //etc etc
  conn.Close();
 }

Your pattern for open and close is correct. 您的打开和关闭模式是正确的。 However you must note that this doesn't open and close the connection to the SQL Server so doesn't really address your concerns over memory usage and CPU - in fact it wont make any difference. 但是,您必须注意,这不会打开和关闭与SQL Server的连接,因此并不能真正解决您对内存使用和CPU的担忧-实际上,这不会产生任何影响。

What Open and Close does is lease and return a connection to the ADO Connection Pool on the client PC. 打开和关闭的作用是租借并返回到客户端PC上ADO连接池的连接。 This means that Closing an ADO connection is not guaranteed (and in most cases will not) close and release the connection to the SQL Server. 这意味着不能保证关闭ADO连接(在大多数情况下不能)关闭并释放与SQL Server的连接。 This is becasue establishing and authenticating a connection is relatively expensive and slow, so the ADO connection pool keeps your connections in a pool, still open, just in case you want to re-establish a connection. 这是因为建立和验证连接相对昂贵且缓慢,因此ADO连接池将您的连接保存在一个仍保持打开状态的池中,以防万一您想重新建立连接。

What makes the difference to SQL Server is the number of concurrent queries it needs to execute - and the dataset size of the queries, and the total size of the data in the database. 与SQL Server的不同之处在于,它需要执行的并发查询的数量-查询的数据集大小,以及数据库中数据的总大小。

Concurrent queries squeeze CPU, and the datasets returned squeeze the RAM available. 并发查询挤压CPU,返回的数据集挤压可用RAM。 Obviously the bigger your database the less can be cached in RAM and so the less likely you are to get a cache hit when querying. 显然,数据库越大,在RAM中缓存的内容就越少,因此查询时缓存命中的可能性就越小。

In practice my experience with SQL Express editions is that you wont notice any difference between it and the full edition of SQL Server unless you are doing some very specific things; 实际上,我对SQL Express版本的经验是,除非您做一些非常具体的事情,否则您不会注意到它与SQL Server完整版之间的任何区别。

1) Writing a BI style tool which allows the user to construct user-defined or user-scoped queries. 1)编写一个BI样式工具,该工具允许用户构造用户定义或用户范围的查询。 2) Writing terrible SQL - "big SQL" may mask your bad query syntax, but Express wont be able to because it has less available RAM to play with. 2)编写糟糕的SQL-“大SQL”可能掩盖了错误的查询语法,但Express无法使用,因为它的可用RAM较少。

If you write efficient, constrained SQL, you probably wont actually ever hit any of SQL Express's limitations. 如果您编写有效的,受约束的SQL,您实际上可能永远不会遇到SQL Express的任何限制。

You'll want to make use of the disposable pattern to ensure everything is closed and disposed properly: 您将要使用一次性模式,以确保一切均已关闭并正确处理:

var query = "select * from ValidId where id=@id";

using (var conn = new System.Data.SqlClient.SqlConnection(usingConnectionString))
using (var command = new System.Data.SqlClient.SqlCommand(query, conn))
{
    command.Parameters.Add("@id", SqlDbType.Int).Value = Id;
    conn.Open;

    using (var reader = command.ExecuteReader())
    {
        while (reader.Read())
        {
            string Test = reader["Id"].ToString();
        }
    }

    command.Parameters.Clear();
}

You don't need to check the connection state; 您无需检查连接状态。 it will close when it's being disposed. 废弃时它将关闭。

One thing to note: it's best practice to explicitly specify your parameter data types. 需要注意的一件事:最佳做法是明确指定参数数据类型。 I've assumed SqlDbType.Int in your case, but you can change it to whatever it really is. 在您的情况下,我假设使用SqlDbType.Int ,但是您可以将其更改为实际的值。

Another thing to note: you don't want to do too much inside the reader while loop. 需要注意的另一件事:while循环中,您不想在阅读器内部做太多事情。 You want to build your collection or whatever and get out of there. 您想构建您的收藏集或其他任何东西,然后离开那里。 The shorter your connection is open, the better. 打开的连接越短越好。 That's because you could potentially be holding a read lock on some of the rows in the database that might affect other users and their applications. 那是因为您可能对数据库中的某些行持有读取锁,这可能会影响其他用户及其应用程序。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM