使用静态适合CRUD操作 [英] Is using static appropriate for CRUD operation

查看:106
本文介绍了使用静态适合CRUD操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个静态类DBO,其中包含用于建立

连接的静态方法GetConnection,用于插入,更新,删除的静态方法IUD以及用于检索数据的静态方法GetTable。如果使用静态方法,则适用于Crud不是我可以使用的。



我尝试过:



I have a static class DBO which contains static method GetConnection for establishing
connection, static method IUD for insert, update, delete and static method GetTable for retrieving data.Is using static for Crud appropriate if not what might I use.

What I have tried:

public static class DBO
   {

       public static SqlConnection GetConnection()
       {
           SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["myconnection"].ConnectionString);
           if (con.State != ConnectionState.Open)
           {
               con.Open();
           }
           return con;
       }

       public static int IUD(string sql, SqlParameter[] param, CommandType cmdType)
       {
           using (SqlConnection con = GetConnection())
           {

               SqlCommand cmd = new SqlCommand(sql, con);
               cmd.CommandType = cmdType;

               if (param != null)
               {
                   cmd.Parameters.AddRange(param);
               }
               try
               {
                   return cmd.ExecuteNonQuery();
               }
               catch (Exception ex)
               {

                   throw ex;
               }

           }
       }
       public static DataTable GetTable(string sql, SqlParameter[] param, CommandType cmdType)
       {
           using (SqlConnection con = GetConnection())
           {
               using (SqlCommand cmd = new SqlCommand(sql, con))
               {
                   cmd.CommandType = cmdType;

                   if (param != null)
                   {
                       cmd.Parameters.AddRange(param);
                   }
                   SqlDataAdapter da = new SqlDataAdapter(cmd);

                   DataTable dt = new DataTable();
                   da.Fill(dt);

                   return dt;

               }
           }
       }

推荐答案

静态很好,你可能遇到的唯一问题是你想要在线上实现单元测试,因为你当前的代码会渲染使用它的任何东西都是不可测试的。此外,调用方法可能更好地自己打开连接,而不是让GetConnection这样做。您应该尽可能短的连接,因此客户端代码最好在实际使用之前打开连接。
Static is fine, the only issue you might have is if you want to implement unit testing down the line as your current code will render anything that uses it untestable. Also it's probably better for the calling methods to open the connection themselves rather than having GetConnection do it. You should have connections as short-lived as possible so it's better for client code to open the connection just before it is actually used.


这篇关于使用静态适合CRUD操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆