【类库】私房干货.Net数据层方法的封装
【類庫(kù)】私房干貨.Net數(shù)據(jù)層方法的封裝
作者:白寧超
時(shí)間:2016年3月5日22:51:47
摘要:繼上篇《Oracle手邊常用70則腳本知識(shí)匯總》文章的發(fā)表,引起很多朋友關(guān)注。便促使筆者收集整理此文。本文主要針是對(duì)微軟技術(shù)對(duì)數(shù)據(jù)庫(kù)(下文案例采用的)操作時(shí),調(diào)用執(zhí)行方法的封裝,這也是數(shù)年逐漸學(xué)習(xí)、吸收、實(shí)踐、完成的一個(gè)類庫(kù)。其中不免有不合理之處,亦或是不符合個(gè)別讀者的使用習(xí)慣。在此,共享此文,權(quán)當(dāng)互相學(xué)習(xí)。(本文原創(chuàng),轉(zhuǎn)載注明出處:私房干貨.Net數(shù)據(jù)層方法的封裝)
1 概述
本文分以下幾個(gè)部分,第一部分概述,整個(gè)文章布局;第二部分介紹類的引用;第三部分介紹公用連接字符串;第四部分分別介紹不含參數(shù)執(zhí)行方法(返回影響行數(shù))、含參數(shù)執(zhí)行方法(返回影響行數(shù))、不含參數(shù)執(zhí)行方法(返回對(duì)象)、含參數(shù)執(zhí)行方法(返回對(duì)象)、不含參數(shù)查詢方法(返回對(duì)象)、含參數(shù)的查詢方法(返回對(duì)象)、調(diào)用存儲(chǔ)過(guò)程的方法(返回對(duì)象)、調(diào)用分頁(yè)的方法;第五部分對(duì)SQL Server的部分核心常用語(yǔ)句進(jìn)行補(bǔ)充;最后附上完整類庫(kù)。
2 類庫(kù)的引用
筆試之前從事net技術(shù),對(duì)類的引用習(xí)慣見(jiàn)到諸如using System;但是這點(diǎn)在后來(lái)至今使用java引用是不一樣的;這也是筆者看到using引用親切之所在。本類引用如下:
using System; //系統(tǒng)類庫(kù) using System.Collections.Generic; using System.Linq; //Linq類庫(kù),對(duì)linq操作使用 using System.Text; using System.Configuration; //數(shù)據(jù)庫(kù)配置使用 using System.Data.SqlClient; using System.Data;諸如以上方法的引用方式,如何使用大家都清楚,但是對(duì)using調(diào)用底層,建議有興趣的朋友參照《C#高級(jí)編程》,此處不是強(qiáng)調(diào)的重點(diǎn),大家知道這些引用即可
3 公用連接字符串
數(shù)據(jù)庫(kù)的連接分為兩種:其一便是寫(xiě)下單頁(yè)面的數(shù)據(jù)庫(kù)連接(即每個(gè)頁(yè)面重復(fù)一樣的連接語(yǔ)句)其二便是在公共資源文件中統(tǒng)一配置,采用如下語(yǔ)句調(diào)用即可:
static string connstr = ConfigurationManager.ConnectionStrings["sql"].ConnectionString; //讀取配置文件中的連接字符串這樣配置的優(yōu)點(diǎn),顯而易見(jiàn),優(yōu)化代碼,減少冗余,便于修改和調(diào)用。相反,逐個(gè)頁(yè)面去寫(xiě)連接語(yǔ)句,如果需要修改,很大的工作量且容易漏改。這里也是強(qiáng)調(diào)封裝好處。
4 類庫(kù)方法逐個(gè)剖析
4.1 不含參數(shù)執(zhí)行方法的封裝(返回影響行數(shù))
本方法執(zhí)行非查詢sql語(yǔ)句,返回受影響行數(shù),如果執(zhí)行非增刪改則返回-1,詳細(xì)內(nèi)容如下:
/// <summary>/// 執(zhí)行非查詢sql語(yǔ)句,返回受影響行數(shù),如果執(zhí)行非增刪改則返回-1/// </summary>/// <param name="sql">sql語(yǔ)句</param>/// <param name="paras">參數(shù)數(shù)組</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 含參數(shù)執(zhí)行方法的封裝(返回影響行數(shù))
本方法執(zhí)行非查詢sql語(yǔ)句,返回受影響行數(shù),如果執(zhí)行非增刪改則返回-1,詳細(xì)內(nèi)容如下:
/// <summary>/// 執(zhí)行非查詢sql語(yǔ)句,返回受影響行數(shù),如果執(zhí)行非增刪改則返回-1/// </summary>/// <param name="sql">sql語(yǔ)句</param>/// <param name="paras">參數(shù)數(shù)組</param>/// <returns>影響行數(shù)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 不含參數(shù)執(zhí)行方法(返回對(duì)象)
本方法執(zhí)行讀取數(shù)據(jù),返回一個(gè)對(duì)象,詳細(xì)方法剖析如下:
/// <summary>/// 執(zhí)行查詢sql語(yǔ)句,返回一個(gè)無(wú)參數(shù)dataset對(duì)象/// </summary>/// <param name="sql">sql語(yǔ)句</param>/// <param name="paras"></param>/// <returns>返回dataset 對(duì)象</returns>public static DataSet GetDataSetNotPara(string sql){DataSet ds = new DataSet();using (SqlConnection conn = new SqlConnection(connstr)){using (SqlCommand cmd = new SqlCommand(sql, conn)){//根據(jù)傳來(lái)的參數(shù)。決定是sql語(yǔ)句還是存儲(chǔ)過(guò)程cmd.CommandType = CommandType.StoredProcedure;conn.Open();using (SqlDataAdapter sda = new SqlDataAdapter(cmd)){sda.Fill(ds);}}}return ds;}4.4 含參數(shù)執(zhí)行方法(返回對(duì)象)
本方法執(zhí)行讀取數(shù)據(jù),返回一個(gè)對(duì)象,詳細(xì)方法剖析如下:
/// <summary>/// 執(zhí)行讀取數(shù)據(jù),返回一個(gè)對(duì)象/// </summary>/// <param name="sql">sql語(yǔ)句</param>/// <param name="paras">參數(shù)數(shù)組</param>/// <returns>返回一個(gè)對(duì)象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 不含參數(shù)查詢方法(返回對(duì)象)
本方法執(zhí)行查詢sql語(yǔ)句,返回一個(gè)無(wú)參數(shù)dataset對(duì)象,詳細(xì)方法剖析如下:
/// <summary>/// 執(zhí)行查詢sql語(yǔ)句,返回一個(gè)無(wú)參數(shù)dataset對(duì)象/// </summary>/// <param name="sql">sql語(yǔ)句</param>/// <param name="paras"></param>/// <returns>返回dataset 對(duì)象</returns>public static DataTable GetDataTableNotPara(string sql){DataTable dt = new DataTable();using (SqlConnection conn = new SqlConnection(connstr)){using (SqlCommand cmd = new SqlCommand(sql, conn)){//根據(jù)傳來(lái)的參數(shù)。決定是sql語(yǔ)句還是存儲(chǔ)過(guò)程conn.Open();using (SqlDataAdapter sda = new SqlDataAdapter(cmd)){sda.Fill(dt);}}}return dt;}4.6 含參數(shù)的查詢方法(返回對(duì)象)
本方法執(zhí)行查詢sql語(yǔ)句,返回一個(gè)參數(shù)dataset對(duì)象,詳細(xì)方法剖析如下:
/// <summary>/// 執(zhí)行查詢sql語(yǔ)句,返回一個(gè)dataset對(duì)象/// </summary>/// <param name="sql">sql語(yǔ)句</param>/// <param name="paras">查詢參數(shù)</param>/// <returns>返回dataset 對(duì)象</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)){//根據(jù)傳來(lái)的參數(shù)。決定是sql語(yǔ)句還是存儲(chǔ)過(guò)程cmd.CommandType = CommandType.StoredProcedure;//添加參數(shù) cmd.Parameters.AddRange(paras);conn.Open();using (SqlDataAdapter sda = new SqlDataAdapter(cmd)){sda.Fill(ds);}}}return ds;}4.7 調(diào)用存儲(chǔ)過(guò)程的方法(返回對(duì)象)
本方法可以執(zhí)行sql語(yǔ)句或存儲(chǔ)過(guò)程,詳細(xì)方法剖析如下:?
/// <summary>/// 可以執(zhí)行sql語(yǔ)句或存儲(chǔ)過(guò)程/// </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)){//根據(jù)傳來(lái)的參數(shù)。決定是sql語(yǔ)句還是存儲(chǔ)過(guò)程cmd.CommandType = CommandType.StoredProcedure;//添加參數(shù)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 調(diào)用分頁(yè)的方法
本方法實(shí)現(xiàn)分頁(yè)功能,詳細(xì)方法剖析如下:
/// <summary>/// 實(shí)現(xiàn)分頁(yè)功能/// </summary>/// <param name="sql">sql語(yǔ)句</param>/// <param name="paras">參數(shù)數(shù)組(顯示index頁(yè)和每頁(yè)顯示條數(shù)size)</param>/// <returns>查詢結(jié)果</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的部分核心常用語(yǔ)句進(jìn)行補(bǔ)充
5.1 去掉重復(fù)行:
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 算術(shù)元算查詢
select grade*(1+0.2) as 總成績(jī),grade/(10) as 績(jī)點(diǎn) from sc
5.6 分組函數(shù)查詢
select COUNT(*) as 總?cè)藬?shù) from student select COUNT(distinct sno) as '選修的總?cè)藬?shù)' from sc select AVG(grade) as '平均成績(jī)' from sc where sno='10021' select MAX(grade) as 'MAX成績(jī)' from sc where sno='10021' select MIN(grade) as 'MIN成績(jī)' from sc where sno='10021' select SUM(grade) as '總成績(jī)' from sc where sno='10021' select SUM(grade)/COUNT(grade) as '平均成績(jī)' from sc where sno='10021' select SUM(grade) as '總成績(jī)' from sc group by sno having sum(grade)>1005.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 '同一個(gè)系' 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 復(fù)合條件連接
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創(chuàng)建用戶
sys.sp_addlogin bnc,bnc,Studets sp_adduser bnc,bnc
--權(quán)限分配和收回
grant select on student to bnc
select * from student
revoke select on student from bnc
5.14 視圖相關(guān)操作
--視圖的創(chuàng)建create view VIEW_STUGrade(學(xué)號(hào),姓名,課程,成績(jī))asselect student.sno,student.sname,course.cname,sc.grade from student,course,scwhere student.sno=sc.sno and course.cno=sc.cno and student.sdept='軟件'--查看視圖select * from VIEW_STUGrade--視圖修改alter view VIEW_STUGrade(學(xué)號(hào),姓名,課程,成績(jī))asselect student.sno,student.sname,course.cname,sc.grade from student,course,scwhere student.sno=sc.sno and course.cno=sc.cno and student.sdept='軟件'with check option--更新失敗后不影響視圖查看--視圖更新update VIEW_STUGrade set 姓名='王超' where 學(xué)號(hào)='10022' select * from student where sno='10022'/* 1,可更新視圖: a,單個(gè)基本表導(dǎo)出的 2,不可更新視圖 a 兩個(gè)以上基本表導(dǎo)出的 b 視圖字段來(lái)自表達(dá)式或者函數(shù) c 嵌套查詢的表 d 分組子句使用distinct */--刪除視圖 drop view VIEW_STUGrade5.15 函數(shù)相關(guān)操作
--創(chuàng)建函數(shù)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 存儲(chǔ)過(guò)程相關(guān)操作
--創(chuàng)建存儲(chǔ)過(guò)程,GO create proc [dbo].[sel] (@sno char(10))asselect * from student where sno=@snoexec sel @sno='10021'--查看GO create proc sel2asselect * from studentexec sel2--修改GO create proc updat @sno char(10), @sex char(2)asupdate student set sex=@sex where sno=@snoselect * from student exec updat @sno='10021', @sex='女'--刪除GO create proc dele @sno char(10)asdelete student where sno=@snoselect * from studentexec dele @sno='10029'--插入GO create proc inser @sno char(10), @sname char(20), @sex char(2), @sage smallint, @sdept char(15)asinsert into student values(@sno,@sname,@sex,@sage,@sdept)exec inser @sno='10029', @sname='tom', @sex='男', @sage=100, @sdept='sc' select * from student View Code5.17 觸發(fā)器相關(guān)操作
--觸發(fā)器 use Studets GO create trigger insert_Tri ON student after insert as print '有新數(shù)據(jù)插入!' GO create trigger update_Tri on student after update as print '有數(shù)據(jù)更新!' ------ GO create trigger delete_Tri on student after delete as print '有數(shù)據(jù)刪除! --修改觸發(fā)器 GO alter trigger delete_Tri on student after delete as if '王帥' in (select sname from deleted) print '該信息不許刪除!' rollback transaction --執(zhí)行存儲(chǔ)過(guò)程查看觸發(fā)器使用情況 exc inser @sno='10029', @sname='王帥', @sex='男', @sage=25, @sdept='國(guó)貿(mào)' exec updat @sno='10029', @sex='女' exec dele @sno='10029' --查看,修改,刪除觸發(fā)器 /* sp_*+觸發(fā)器名稱 sp_helptext:觸發(fā)器正文信息 sp_help:查看一般信息,觸發(fā)器名稱,屬性,創(chuàng)建時(shí)間,類型 sp_depends:引用或指定表的所有觸發(fā)器 sp_helptrigger:指定信息 */ sp_help delete_Tri sp_helptext delete_Tri sp_depends delete_Tri sp_helptrigger student --刪除觸發(fā)器 drop trigger delete_Tri6 類庫(kù)源碼分享
數(shù)據(jù)層類庫(kù)封裝源碼 訪問(wèn)密碼 023d
轉(zhuǎn)載于:https://www.cnblogs.com/baiboy/p/sql1.html
總結(jié)
以上是生活随笔為你收集整理的【类库】私房干货.Net数据层方法的封装的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。