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

后端 未结 3 1651
粉色の甜心
粉色の甜心 2021-01-23 06:36

I would like to know what could be best approach to open a SqlConnection with Sql Server 2008R2 Express Edition Database. This Version of Sql has Limit

相关标签:
3条回答
  • 2021-01-23 07:09

    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.

    Another thing to note: you don't want to do too much inside the reader while loop. 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.

    0 讨论(0)
  • 2021-01-23 07:15

    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.

    What Open and Close does is lease and return a connection to the ADO Connection Pool on the client PC. 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. 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.

    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.

    Concurrent queries squeeze CPU, and the datasets returned squeeze the RAM available. 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.

    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;

    1) Writing a BI style tool which allows the user to construct user-defined or user-scoped queries. 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.

    If you write efficient, constrained SQL, you probably wont actually ever hit any of SQL Express's limitations.

    0 讨论(0)
  • 2021-01-23 07:25

    Just use using as it disposes of the connection once done.

     using(SqlConnection conn = new SqlConnection("Connection string")){
      //do sql stuff
      conn.Open(); 
      //etc etc
      conn.Close();
     }
    
    0 讨论(0)
提交回复
热议问题