Do I need to get rid of MySqlCommand?

I find it incredibly unpleasant to write usage instructions for each of my queries (which require their own command or write parameters.clear ()), which sometimes require variable declarations outside the usage block. Its so incredibly annoying and looks a lot messier compared to the version without disposing of the object.

Do I need to get rid of him? what happens if i don't? I know that its good practice to dispose of an object when it has this interface.

+3
source share
2 answers

Reflector CloseStatement() , Dispose() , System.ComponentModel.Component. - NativeDriver.CloseStatement32 (id), .

, . ?

, . , using "", - , ​​ - . , , , .

+4

ASP.NET, Connect() ( ), . , , .

Exec SQL typafe - .

using System;
using System.Web;
using System.Data.SqlClient;
using Conf = System.Configuration.ConfigurationManager;
using System.Data;

public static class Sql {
    public static SqlConnection Connect() {
        // create & open connection
        SqlConnection result = new SqlConnection(Conf.ConnectionStrings["connectionString"].ConnectionString);
        result.Open();

        // add delegate to trigger when page has finished, to close the connection if it still exists
        System.Web.UI.Page page = HttpContext.Current.Handler as System.Web.UI.Page;
        if (page != null) {
            page.Unload += (EventHandler)delegate(object s, EventArgs e) {
                try {
                    result.Close();
                } catch (Exception) {
                } finally {
                    result = null;
                }
            };
        }

        // return connection
        return result;
    }

    public static SqlDataReader Exec(string name, params object[] parameters) {
        using (SqlCommand cmd = Connect().CreateCommand()) {
            cmd.CommandTimeout = int.Parse(Conf.AppSettings["commandTimeoutSec"]);
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = name;
            for (int x = 0; x + 1 < parameters.Length; x += 2) {
                SqlParameter p = cmd.Parameters.AddWithValue((string)parameters[x], parameters[x + 1]);
                if (parameters[x + 1] is string) {
                    p.DbType = DbType.AnsiString;
                }
            }
            return cmd.ExecuteReader(CommandBehavior.CloseConnection);
        }
    }

    public static void Test() {
        using (SqlDataReader reader = Exec(
            "SELECT * FROM member WHERE name=@firstname AND age=YEAR(GETDATE())-@yearborn",
            "@firstname", "tom",
            "@yearborn", 1978)) {
            while (reader.Read()) {
                // read
            }
        }
    }
}
+2

Source: https://habr.com/ru/post/1746892/


All Articles