SqlHelper重構,sqlhelper

來源:互聯網
上載者:User

SqlHelper重構,sqlhelper

在機房重構的時候有用到SqlHelper(點擊查看),當時什麼都不懂。後來經過不斷的使用,開始理解其中的意思。後來發現原來的SqlHelper寫的有點繁瑣。對於每個操作都需要寫兩次,來區分是否帶參數。這次,重構一版,來改善一下它的缺點。


長度可變參數params

首先,我們來看一下長度可變參數params。舉兩個例子來說明 

第一個

<span style="font-size:18px;"><span style="font-size:18px;">class Program    {        static void Main(string[] args)        {            int i = Sum(new int[]{2,87,51,5});            Console.WriteLine(i);            Console.ReadKey();        }        static int Sum(int[] sums)        {            int result = 0;            foreach (int i in sums )            {                result += i;                }            return result;        }    }</span></span>
執行後返回結果為


第二個:

<span style="font-size:18px;">class Program    {        static void Main(string[] args)        {            int i = Sum(2,5,5,5);            Console.WriteLine(i);            Console.ReadKey();        }        static int Sum(params int[] sums)        {            int result = 0;            foreach (int i in sums )            {                result += i;                }            return result;        }    }</span>
執行後返回結果為:



其中第一個例子中的Sum方法,在聲明的時候沒有用params修飾符,所以調用的時候需要聲明數組。而第二個例子中用了params修飾符,調用的時候,直接輸入參數即可。這時就可以來體會一下params的作用了。params將其後所有參數打包,相當於一個數組。如果沒有寫參數的話,它相當於長度為0的數組。

註:聲明params數組時,該數組必須在參數的最後一個,因為它預設會對其後面的所有參數打包。

同理,就可以在SqlHelper的方法中使用params修飾符了。如果有參數,輸入參數即可,沒有參數就不用輸入,相當於長度為0的數組。

使用using()

在資料庫執行完成後,需要執行conn.close()和cmd.Dispose()操作。在之前的SqlHelper中,是要將這兩句代碼寫出來的。其實還有更好的方法來代替它。就是使用using(),using()方法實現了IDispose介面,也就是說,如果使用using(),它會自動協助我們執行了conn.close()和cmd.Dispose()操作。下面,看我重構後的SqlHelper

<span style="font-size:18px;"><span style="font-size:18px;">using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Configuration;using System.Data.SqlClient;using System.Data;namespace DAL{    public class SqlHelper    {        //app.config檔案的繼承:        public static readonly string connstr =            ConfigurationManager.ConnectionStrings["connstr"].ConnectionString;        /// <summary>        /// 執行增刪改的SQL語句或預存程序        /// </summary>        /// <param name="cmdText">SQL語句或預存程序名稱</param>        /// <param name="parameters">參數</param>        /// <returns>返回受影響的行數</returns>        public int ExecuteNonQuery(string cmdText, CommandType cmdType,            params SqlParameter[] parameters)//在SqlParameter[]前面加上了長度可變參數--params修飾符。</span>        {            try            {   //建立SQL串連                using (SqlConnection conn = new SqlConnection(connstr))                {                    //開啟串連                    conn.Open();                    //建立SqlCommand,執行SQL指令                    using (SqlCommand cmd = conn.CreateCommand())                    {                        //SQL語句或預存程序名稱                        cmd.CommandText = cmdText;                        //命令類型                        cmd.CommandType = cmdType;                        //添加參數                        cmd.Parameters.AddRange(parameters);                        //返回執行結果                        return cmd.ExecuteNonQuery();                    }                }            }            catch (Exception ex)            {                //拋出異常                throw new Exception(ex.ToString());            }        }        /// <summary>        /// 執行對資料庫的查操作        /// </summary>        /// <param name="cmdText">SQL語句或預存程序</param>        /// <param name="cmdType">命令類型</param>        /// <param name="parameters">參數</param>        /// <returns>返回查詢到的表</returns>        public DataTable ExecuteDataTable(string cmdText, CommandType cmdType,            params SqlParameter[] parameters)//在SqlParameter[]前面加上了長度可變參數--params修飾符。        {            try            {                //建立SQL串連                using (SqlConnection conn = new SqlConnection(connstr))                {                    //開啟串連                    conn.Open();                    //建立SqlCommand,執行SQL指令                    using (SqlCommand cmd = conn.CreateCommand())                    {                        //SQL語句或預存程序名稱                        cmd.CommandText = cmdText;                        //命令類型                        cmd.CommandType = cmdType;                        //添加參數                        cmd.Parameters.AddRange(parameters);                        //定義資料集                        DataSet dataset = new DataSet();                        //建立資料配接器,執行查詢                        SqlDataAdapter adapter = new SqlDataAdapter(cmd);                        //填充資料集                        adapter.Fill(dataset);                        //擷取資料集中的第一個表                        return dataset.Tables[0];                    }                }            }            catch (Exception ex)            {                //拋出異常                throw new Exception(ex.ToString());            }        }    }}</span></span>

總結:

在這次重構中又學到了長度可變參數params和加深了對using()方法的理解。感覺還是蠻不錯的。當然,並不見得重構的SqlHelper就多麼的好,不懂的東西。還有很多,以後還要不斷的學習來擴從自己。


相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.