1. 程式人生 > >【類庫】私房乾貨.Net資料層方法的封裝

【類庫】私房乾貨.Net資料層方法的封裝

作者:白寧超

時間:2016年3月5日22:51:47

摘要:繼上篇《Oracle手邊常用70則指令碼知識彙總》文章的發表,引起很多朋友關注。便促使筆者收集整理此文。本文主要針是對微軟技術對資料庫(下文案例採用的)操作時,呼叫執行方法的封裝,這也是數年逐漸學習、吸收、實踐、完成的一個類庫。其中不免有不合理之處,亦或是不符合個別讀者的使用習慣。在此,共享此文,權當互相學習。(本文原創,轉載註明出處:私房乾貨.Net資料層方法的封裝

1 概述

本文分以下幾個部分,第一部分概述,整個文章佈局;第二部分介紹類的引用;第三部分介紹公用連線字串;第四部分分別介紹不含引數執行方法(返回影響行數)、含引數執行方法(返回影響行數)、不含引數執行方法(返回物件)、含引數執行方法(返回物件)、不含引數查詢方法(返回物件)、含引數的查詢方法(返回物件)、呼叫儲存過程的方法(返回物件)、呼叫分頁的方法;第五部分對SQL Server的部分核心常用語句進行補充;最後附上完整類庫。

2 類庫的引用

筆試之前從事net技術,對類的引用習慣見到諸如using System;但是這點在後來至今使用java引用是不一樣的;這也是筆者看到using引用親切之所在。本類引用如下:

using System; //系統類庫
using System.Collections.Generic;
using System.Linq; //Linq類庫,對linq操作使用
using System.Text;
using System.Configuration; //資料庫配置使用
using System.Data.SqlClient;
using System.Data;

諸如以上方法的引用方式,如何使用大家都清楚,但是對using呼叫底層,建議有興趣的朋友參照《C#高階程式設計》,此處不是強調的重點,大家知道這些引用即可

3 公用連線字串

資料庫的連線分為兩種:其一便是寫下單頁面的資料庫連線(即每個頁面重複一樣的連線語句)其二便是在公共資原始檔中統一配置,採用如下語句呼叫即可:

static string connstr = ConfigurationManager.ConnectionStrings["sql"].ConnectionString; //讀取配置檔案中的連線字串

這樣配置的優點,顯而易見,優化程式碼,減少冗餘,便於修改和呼叫。相反,逐個頁面去寫連線語句,如果需要修改,很大的工作量且容易漏改。這裡也是強調封裝好處。

4 類庫方法逐個剖析

4.1 不含引數執行方法的封裝(返回影響行數)

本方法執行非查詢sql語句,返回受影響行數,如果執行非增刪改則返回-1,詳細內容如下:

       /// <summary>
        /// 執行非查詢sql語句,返回受影響行數,如果執行非增刪改則返回-1
        /// </summary>
        /// <param name="sql">sql語句</param>
        /// <param name="paras">引數陣列</param>
         public static int ExecuteNonParaQuery(string sql)
         {
             int res = -1;
             using (SqlConnection conn = new SqlConnection(connstr))
             {
                 using (SqlCommand cmd = new SqlCommand(sql, conn))
                 {
                     conn.Open();
                     res = cmd.ExecuteNonQuery();
                 }
             }
             return res;
         }

4.2 含引數執行方法的封裝(返回影響行數)

本方法執行非查詢sql語句,返回受影響行數,如果執行非增刪改則返回-1,詳細內容如下:

        /// <summary>
        /// 執行非查詢sql語句,返回受影響行數,如果執行非增刪改則返回-1
        /// </summary>
        /// <param name="sql">sql語句</param>
        /// <param name="paras">引數陣列</param>
        /// <returns>影響行數res</returns>
        public static int ExecuteNonQuery(string sql, params SqlParameter[] paras)
        {
            int res = -1;
            using (SqlConnection conn = new SqlConnection(connstr))
            {
                using (SqlCommand cmd = new SqlCommand(sql, conn))
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    if (paras != null || paras.Length > 0)
                    {
                        cmd.Parameters.AddRange(paras);
                    }
                    conn.Open();
                    res = cmd.ExecuteNonQuery();
                }
            }
            return res;
        }

4.3 不含引數執行方法(返回物件)

本方法執行讀取資料,返回一個物件,詳細方法剖析如下:

        /// <summary>
         /// 執行查詢sql語句,返回一個無引數dataset物件
         /// </summary>
         /// <param name="sql">sql語句</param>
         /// <param name="paras"></param>
         /// <returns>返回dataset 物件</returns>
         public static DataSet GetDataSetNotPara(string sql)
         {
             DataSet ds = new DataSet();
             using (SqlConnection conn = new SqlConnection(connstr))
             {
                 using (SqlCommand cmd = new SqlCommand(sql, conn))
                 {
                     //根據傳來的引數。決定是sql語句還是儲存過程
                     cmd.CommandType = CommandType.StoredProcedure;
                     conn.Open();
                     using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
                     {
                         sda.Fill(ds);
                     }
                 }
             }
             return ds;
         }

4.4 含引數執行方法(返回物件)

本方法執行讀取資料,返回一個物件,詳細方法剖析如下:

         /// <summary>
         /// 執行讀取資料,返回一個物件
         /// </summary>
         /// <param name="sql">sql語句</param>
         /// <param name="paras">引數陣列</param>
         /// <returns>返回一個物件o</returns>
         public static object ExecuteScalar(string sql, params SqlParameter[] paras)
         {
             object  o = null;
             using (SqlConnection conn = new SqlConnection(connstr))
             {
                 using (SqlCommand cmd = new SqlCommand(sql, conn))
                 {
                     cmd.CommandType = CommandType.StoredProcedure;
                     if (paras != null)
                     {
                         cmd.Parameters.AddRange(paras);
                     }
                     conn.Open();
                     o = cmd.ExecuteScalar();
                 }
             }
             return o;
         }

4.5 不含引數查詢方法(返回物件)

本方法執行查詢sql語句,返回一個無引數dataset物件,詳細方法剖析如下:

         /// <summary>
         /// 執行查詢sql語句,返回一個無引數dataset物件
         /// </summary>
         /// <param name="sql">sql語句</param>
         /// <param name="paras"></param>
         /// <returns>返回dataset 物件</returns>
         public static DataTable  GetDataTableNotPara(string sql)
         {
             DataTable dt = new DataTable();
             using (SqlConnection conn = new SqlConnection(connstr))
             {
                 using (SqlCommand cmd = new SqlCommand(sql, conn))
                 {
                     //根據傳來的引數。決定是sql語句還是儲存過程
                  
                     conn.Open();
                     using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
                     {
                         sda.Fill(dt);
                     }
                 }
             }
             return dt;
         }

4.6 含引數的查詢方法(返回物件)

本方法執行查詢sql語句,返回一個引數dataset物件,詳細方法剖析如下:

        /// <summary>
         /// 執行查詢sql語句,返回一個dataset物件
         /// </summary>
         /// <param name="sql">sql語句</param>
         /// <param name="paras">查詢引數</param>
         /// <returns>返回dataset 物件</returns>
         public static DataSet GetDataSet(string sql, params SqlParameter[] paras)
         {
             DataSet  ds = new DataSet();
             using (SqlConnection conn = new SqlConnection(connstr))
             {
                 using (SqlCommand cmd = new SqlCommand(sql, conn))
                 {
                     //根據傳來的引數。決定是sql語句還是儲存過程
                     cmd.CommandType = CommandType.StoredProcedure;
                     //新增引數
                     cmd.Parameters.AddRange(paras);
                     conn.Open();
                     using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
                     {
                         sda.Fill(ds);
                     }
                 }
             }
             return ds;
         }

4.7 呼叫儲存過程的方法(返回物件)

本方法可以執行sql語句或儲存過程,詳細方法剖析如下: 

        /// <summary>
         /// 可以執行sql語句或儲存過程
         /// </summary>
         /// <param name="text"></param>
         /// <param name="ct"></param>
         /// <param name="param"></param>
         /// <returns></returns>
         public static DataTable ProcGetTable(string sql, params SqlParameter[] param)
         {
             DataTable dt = new DataTable();

             using (SqlConnection conn = new SqlConnection(connstr))
             {
                 using (SqlCommand cmd = new SqlCommand(sql, conn))
                 {
                     //根據傳來的引數。決定是sql語句還是儲存過程
                     
                     cmd.CommandType = CommandType.StoredProcedure;
                     //新增引數
                     cmd.Parameters.AddRange(param);
                     //cmd.Parameters.Add("@name", SqlDbType.NVarChar, 20).Value = param[0];
                     //cmd.Parameters.Add("@pwd", SqlDbType.NVarChar, 20).Value = param[1];
                     conn.Open();
                     using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
                     {
                         sda.Fill(dt);
                     }
                 }
             }
             return dt;
         }

4.8 呼叫分頁的方法

本方法實現分頁功能,詳細方法剖析如下:

        /// <summary>
         /// 實現分頁功能
         /// </summary>
         /// <param name="sql">sql語句</param>
         /// <param name="paras">引數陣列(顯示index頁和每頁顯示條數size)</param>
         /// <returns>查詢結果</returns>
         public static DataTable GetParaTable(string sql, params SqlParameter[] paras)
         {
             DataSet ds = new DataSet();
             using (SqlConnection conn = new SqlConnection(connstr))
             {
                 using (SqlDataAdapter da = new SqlDataAdapter(sql, conn))
                 {
                     if (paras != null)
                     {
                         da.SelectCommand.Parameters.AddRange(paras);
                     }
                     da.SelectCommand.CommandType = CommandType.StoredProcedure;
                     da.Fill(ds);
                 }
             }
             return ds.Tables[0];
         }
    }
}

5 SQL Server的部分核心常用語句進行補充

5.1 去掉重複行

select distinct 欄位 from 表

5.2 格式化查詢

select sname as '姓名',2013-sage as '出生日期' from student

select sname,'出生日期',2013-sage   from student

select 姓名=sname,出生日期=2013-sage  from student

5.3 條件查詢

select * from course where ccredit>3

select * from course where ccredit between 2 and 5

select * from course where ccredit> 2 and ccredit<5

select * from course where ccredit in(2)

select * from course where ccredit  not in(2)

5.4 匹配查詢

select * from student  where sname like '劉__'

select * from student  where sname like '_表__'

select * from student  where sname like '%表%'

5.5 算術元算查詢

select grade*(1+0.2) as 總成績,grade/(10) as 績點 from sc

5.6 分組函式查詢

select COUNT(*) as 總人數 from student
select COUNT(distinct sno) as '選修的總人數' from sc
select AVG(grade) as '平均成績' from sc where sno='10021'
select MAX(grade) as 'MAX成績' from sc where sno='10021'
select MIN(grade) as 'MIN成績' from sc where sno='10021'
select SUM(grade) as '總成績' from sc where sno='10021'
select SUM(grade)/COUNT(grade) as '平均成績' from sc where sno='10021'
select SUM(grade) as '總成績' from sc group by sno  having sum(grade)>100 

5.7 等值連線

select distinct student.*,sc.* from student,sc where student.sno=sc.sno

5.8 自身連線

select distinct A.*,B.* from student A,sc B where A.sno=B.sno

select B.sname as '同一個系' from student A,student B where A.sname='白居易' and A.sdept=B.sdept

5.9 外連線

select A.*,B.* from student  A left join sc B on A.sno=B.sno

select A.*,B.* from student  A right join sc B on A.sno=B.sno

select A.*,B.* from student  A FULL join sc B on A.sno=B.sno

5.10 複合條件連線

select * from sc select * from course

select distinct  A.*,B.* from student A,sc B where A.sno=B.sno and B.grade>99 and B.cno='002'

select distinct  A.*,B.*,C.* from student A,sc B,course C where A.sno=B.sno and B.cno=C.cno and B.grade>99 and B.cno='002'

5.11 字串連線查詢

select sname+sno from student

select distinct sname from student ,sc where student.sno=sc.sno

select  sname from student ,sc where student.sno=sc.sno and student.sno not in (select sno from sc where grade<60) group by sname

5.12 子查詢

select * from student where sage>(select AVG(sage) from student)

5.13 sql建立使用者

sys.sp_addlogin bnc,bnc,Studets sp_adduser bnc,bnc

--許可權分配和收回

grant select on student to bnc

select * from student

revoke select on student from bnc

5.14 檢視相關操作

--檢視的建立

create view VIEW_STUGrade(學號,姓名,課程,成績)

as

select student.sno,student.sname,course.cname,sc.grade from student,course,sc

where student.sno=sc.sno and course.cno=sc.cno and student.sdept='軟體'

--檢視檢視

select * from VIEW_STUGrade

--檢視修改

alter view VIEW_STUGrade(學號,姓名,課程,成績)

as

select student.sno,student.sname,course.cname,sc.grade from student,course,sc

where student.sno=sc.sno and course.cno=sc.cno and student.sdept='軟體'

with check option

--更新失敗後不影響檢視檢視

--檢視更新

update VIEW_STUGrade set 姓名='王超' where 學號='10022' select * from student where  sno='10022'

/* 1,可更新檢視:   a,單個基本表匯出的 2,不可更新檢視   a 兩個以上基本表匯出的   b 檢視欄位來自表示式或者函式   c 巢狀查詢的表   d 分組子句使用distinct */

--刪除檢視 drop view VIEW_STUGrade

5.15 函式相關操作

--建立函式

CREATE FUNCTION GetTime (    @date1 datetime,   @date2 datetime )
RETURNS TABLE
AS RETURN (  
select datediff(dd,@date1,@date2) 日差,datediff(mm,@date1,@date2) 月差,  datediff(yy,@date1,@date2) 年差
)

5.16 儲存過程相關操作

--建立儲存過程,

GO create proc [dbo].[sel] (

@sno char(10)

)

as

select * from student where sno=@sno

exec sel @sno='10021'

--檢視

GO create proc sel2

as

select * from student

exec sel2

--修改

GO create proc updat @sno char(10), @sex char(2)

as

update student set [email protected] where sno=@sno

select * from student  exec updat @sno='10021', @sex=''

--刪除

GO create proc dele @sno char(10)

as

delete student where sno=@sno

select * from student

exec dele @sno='10029'

--插入

GO create proc inser @sno char(10), @sname char(20), @sex char(2), @sage smallint, @sdept char(15)

as

insert into student values(@sno,@sname,@sex,@sage,@sdept)

exec inser @sno='10029', @sname='tom', @sex='', @sage=100, @sdept='sc' select * from student
View Code

5.17 觸發器相關操作

--觸發器
use Studets
GO create trigger insert_Tri
ON student  after
insert as print '有新資料插入!'
GO create trigger update_Tri
on student after
update as print '有資料更新!'
------
GO create trigger delete_Tri
on student after
delete as print '有資料刪除!
--修改觸發器
GO alter trigger delete_Tri
on student after delete
as
if '王帥' in (select sname from deleted)
print '該資訊不許刪除!'
rollback transaction
--執行儲存過程檢視觸發器使用情況
exc inser @sno='10029', @sname='王帥', @sex='男', @sage=25, @sdept='國貿'
exec updat @sno='10029', @sex='女'
exec dele @sno='10029'
--檢視,修改,刪除觸發器
/*   sp_*+觸發器名稱
sp_helptext:觸發器正文資訊   sp_help:檢視一般資訊,觸發器名稱,屬性,建立時間,型別   sp_depends:引用或指定表的所有觸發器   sp_helptrigger:指定資訊 */  sp_help delete_Tri  
sp_helptext delete_Tri
sp_depends delete_Tri  
sp_helptrigger student    
--刪除觸發器  
drop trigger delete_Tri  

6 類庫原始碼分享

相關推薦

私房乾貨.Net資料方法封裝

作者:白寧超 時間:2016年3月5日22:51:47 摘要:繼上篇《Oracle手邊常用70則指令碼知識彙總》文章的發表,引起很多朋友關注。便促使筆者收集整理此文。本文主要針是對微軟技術對資料庫(下文案例採用的)操作時,呼叫執行方法的封裝,這也是數年逐漸學習、吸收、實踐、完成的一個類庫。其中不免

iOS開發深入MVC---UITableView的資料來源方法封裝

一、在iOS開發中,MVC模式是再經典不過的了,本文將從tableview的使用以及自定義cell結合來感受MVC設計模式。 1、在ZPMainController.m檔案中 (1)通過懶載入獲取到模型資料,儲存到陣列helps中 <span style="font

Muduobase一、Timestamp

second 一個 macro fin ftime mac cat gap base 一、Timestamp類 1、類圖如下: 2、 知識點 (1) 這個類繼承了 muduo::copyable, 以及 boost::less_than_comparable.

《瘋狂Java講義(第4版)》-----第7章Java基礎

筆者認為,《瘋狂Java講義(第4版)》這本書的前6章是Java語言的核心,前4章是結構化程式設計的核心,第5章和第6章是Java面向物件的核心。從第七章開始,都是在這些核心基礎知識上的擴充套件了,很多內容可以先熟悉一遍即可,用的時候多查本書以及多檢視官方文件即

第三方JBoss

是一個基於J2EE的開放原始碼的應用伺服器。 JBoss程式碼遵循LGPL許可,可以在任何商業應用中免費使用。JBoss是一個管理EJB的容器和伺服器,支援EJB 1.1、EJB 2.0和EJB3的規範。但JBoss核心服務不包括支援servlet/JSP的WEB容器,一般

第三方Apache Curator

Curator是Netflix公司開源的一個Zookeeper客戶端,與Zookeeper提供的原生客戶端相比,Curator的抽象層次更高,簡化了Zookeeper客戶端的開發量。 包含一下幾個模

第三方Java Guava , Google Guava

類庫集合的擴充套件專案,包括 collections, caching, primitives support, concurrency libraries, common annotations,

做題zoj3649 Social Net——倍增

pre wap mes 最小值 == lag bits 但我 bool 這題是吳老師推薦的,於是我就去做了。 根據題意,在完成最大生成樹後,對於樹上從x到y的一條路徑,求出最大的ck-cj(j<=k,ci為路徑上第i個點的權值)。 我一開始的想法是二分,記路徑xy的中

PHP不使用Excel第三方,如何簡易匯出資料

使用場景 不使用Excel第三方類庫, 需要匯出資料庫中某幾個列的資料,只需將查出每條資料的每列使用英文逗號隔開即可 前言 此方式主要是利用.csv字尾的檔案簡易匯出資料方法 csv介紹 CSV(Comma Separated Valu

小程式分頁載入資料,下拉載入更多,上拉重新整理

【 小程式】分頁載入資料,下拉載入更多,上拉重新整理 分頁載入的優點就不多說了,下面主要記錄一下幾個問題點。 scroll-view元件不能用在頁面根佈局中,不然觸發不了系統的onPullDownRefresh()、onReachBottom()回撥。 在Page頁

讀書筆記安全儲存使用者資料

文章:後端應該如何安全地儲存使用者資料? 總結: 一、使用者資訊之密碼 講密碼的儲存方案前,先要記住三條前提: 使用者喜歡到處使用一樣的密碼 使用者喜歡使用簡單好記的密碼 世界上沒有絕對的安全,但當攻擊成本遠高於收益時,整個系統達到相對安全  

資料庫視訊第六章 資料查詢和管理

一、簡單的SELECT語句 語法格式: SELECT [ALL|DISTINCT] select_list [INTO new_table] FROM table_source [WHERE search_conditions] [GROUP

c++(三)模板

【1】型別進行引數化,模板的意義是什麼? 可以定義型別變數,來接受使用者傳入的型別 template<> : 定義模板引數列表 typename T,typename E, typenameR  :型別變數,可以定義很多,用逗號分隔 &nb

文彬區塊鏈 + 大資料:EOS儲存

原文連結:https://www.cnblogs.com/Evsward/p/storage.html 談到區塊鏈的儲存,我們很容易聯想到它的鏈式儲存結構,然而區塊鏈從比特幣發展到今日當紅的EOS,技術形態已經演化了10年之久。目前的EOS的儲存除了確認結構的鏈式儲存以外,在狀態

GDAL學習更多柵格資料處理函式——滑動視窗與過濾器

例如設計一個3 x 3的滑動視窗,寫演算法執行就有兩種方式: 1.pixel by piexl每個進行逐畫素運算,效率太低,速度慢 2.使用 slice切片形式迴圈,效率高,速度快  兩個作業就是分別用pixel和slice方式完成高通濾波操作進行對比 1.As

座標系雜談投影后的資料如何去除投影?

網友有時候的問題很奇葩,但是這也給了我一個思考的餘地: 既然GCS能投影到PCS,那麼為什麼PCS不能恢復到GCS呢?我們知道,ArcGIS的向量要素一旦投影完畢,就不能再恢復到其本身的GCS,只能進行投影轉換了。 有人說當然可以,反解不就行了嗎? 我想說,你累嗎?反解公式就能累死人,而且還不一定好找。 今

重溫基礎1.語法和資料型別

最近開始把精力放在重新複習JavaScript的基礎知識上面,不再太追求各種花枝招展的前端框架,框架再多,適合實際專案才是最重要。 上星期在掘金髮布了幾篇文章,其中最大塊算是 【複習資料】ES6/ES7/ES8/ES9資料整理(個人整理),也是讓我好好把這些規範複習了一遍,雖然不是完全的原創,而是自己的一些複

C語言typedef(自定義資料型別)與#define(巨集定義)用法比較

  不管是在C語言還是在C++中,typedef這個詞都不少見,當然出現頻率較高的還是在C程式碼中。typedef和#define有些相似,但更多的是不同,特別是在一些複雜的用法上,就完全不同了。      1.巨集定義(#define)      巨集定義又稱為巨集代換

緊跟時代建立asp.net core angular專案

需要安裝node.js,如何安裝請自行百度  1、使用vs2017 建立專案,選擇ASP.NET Core Web應用程式,名稱為:ASPNetAngularDemo 選擇angular專案,可以看到是 .NET Core  版本:ASP.NET Core 2.0 

pythonmatplotlib視覺化

官網《—— 本po環境 maxos 10.12.3 python2.7 模組下載,python2 pip install matplotlib 如果是python3 pip3 install matplotlib pyplot模組 impo