c# sql what to dispose

后端 未结 6 1267
南旧
南旧 2021-01-06 00:10

I have the code below to query records from a stored procedure but am concerned I may not be disposing what I need to or am disposing when the object would be cleared by the

6条回答
  •  遥遥无期
    2021-01-06 00:48

    If you use something like this:

    public void GetData(string studentID)
    {
        using (SqlConnection connection = new SqlConnection(Settings.Default.connectionString))
        {
            connection.Open();
    
            using (SqlCommand command = connection.CreateCommand())
            {
                command.CommandType = CommandType.StoredProcedure;
                command.CommandText = "sp_stored_proc";
                command.Parameters.AddWithValue("@student_id", studentID);
    
                using (SqlDataReader dataReader = command.ExecuteReader())
                {
                    // do something with the data
                }
            }
        }
    }
    

    then all of your Disposable objects will get disposed of correctly. Calling Dispose() on the SqlConnection, SqlCommand and SqlDataReader objects (which is what the using block does when it exits) closes them correctly.

    Additionally, this approach keeps all of your variables scoped to where they are used.

    The downside to this approach is that if you need error handling using a try/catch, you have to either wrap it around the whole method body, or use several of them to handle connection errors differently from reading errors, etc...

提交回复
热议问题