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

后端 未结 3 1687
粉色の甜心
粉色の甜心 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.

提交回复
热议问题