C#的通用DbHelper類(支持?jǐn)?shù)據(jù)連接池)示例詳解
每次新項(xiàng)目的時(shí)候,都要從頭去找一遍數(shù)據(jù)庫(kù)工具類。這里分享一個(gè)簡(jiǎn)單實(shí)用的C#的通用DbHelper工具類,支持?jǐn)?shù)據(jù)連接池。
連接池配置
<connectionStrings> <add name="dh_web" connectionString="Data Source=xxx.com;Initial Catalog=xx_db;User ID=xx;Password=**; pooling=true;max pool size=200" providerName="System.Data.SqlClient"/> </connectionStrings>
DbHelper類
public class DBHelper
{
private static string connectionString = ConfigurationManager.ConnectionStrings["dh_web"].ConnectionString;
//不帶參數(shù)的執(zhí)行命令
public static int ExecuteCommand(string safeSql)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand cmd = new SqlCommand(safeSql, connection);
return cmd.ExecuteNonQuery();
}
}
//帶參數(shù)的執(zhí)行命令
public static int ExecuteCommand(string sql, params SqlParameter[] values)
SqlCommand cmd = new SqlCommand(sql, connection);
cmd.Parameters.AddRange(values);
public static int GetScalar(string safeSql)
return Convert.ToInt32(cmd.ExecuteScalar());
public static int GetScalar(string sql, params SqlParameter[] values)
public static SqlDataReader GetReader(string safeSql)
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
SqlCommand cmd = new SqlCommand(safeSql, connection);
return cmd.ExecuteReader(CommandBehavior.CloseConnection);
public static SqlDataReader GetReader(string sql, params SqlParameter[] values)
SqlCommand cmd = new SqlCommand(sql, connection);
cmd.Parameters.AddRange(values);
public static DataTable GetDataSet(string safeSql)
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
return ds.Tables[0];
public static DataTable GetDataSet(string sql, params SqlParameter[] values)
{
}注意:
CommandBehavior.CloseConnection解決了流讀取數(shù)據(jù)模式下,數(shù)據(jù)庫(kù)連接不能有效關(guān)閉的情況.
當(dāng)某個(gè)XXXDataReader對(duì)象在生成時(shí)使用了CommandBehavior.CloseConnection,那數(shù)據(jù)庫(kù)連接將在XXXDataReader對(duì)象關(guān)閉時(shí)自動(dòng)關(guān)閉.
到此這篇關(guān)于C#的通用DbHelper類(支持?jǐn)?shù)據(jù)連接池)的文章就介紹到這了,更多相關(guān)C#通用DbHelper類內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Unity3D使用UGUI開(kāi)發(fā)原生虛擬搖桿
這篇文章主要為大家詳細(xì)介紹了Unity3D使用UGUI開(kāi)發(fā)原生虛擬搖桿,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-04-04
c#判斷網(wǎng)絡(luò)連接狀態(tài)的示例分享
這篇文章主要介紹了使用c#判斷網(wǎng)絡(luò)連接狀態(tài)的示例,需要的朋友可以參考下2014-02-02
WinForm實(shí)現(xiàn)狀態(tài)欄跑馬燈效果的方法示例
這篇文章主要介紹了WinForm實(shí)現(xiàn)狀態(tài)欄跑馬燈效果的方法,涉及WinForm控件結(jié)合時(shí)間函數(shù)動(dòng)態(tài)操作元素屬性的相關(guān)技巧,需要的朋友可以參考下2017-07-07
C#實(shí)現(xiàn)基于任務(wù)的異步編程模式
本文詳細(xì)講解了C#實(shí)現(xiàn)基于任務(wù)的異步編程模式,文中通過(guò)示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-04-04
C#實(shí)現(xiàn)添加多行文本水印到Word文檔
一般情況下,在Word中添加文字水印僅支持添加一個(gè)文本字樣的水印,由于對(duì)不同文檔的設(shè)計(jì)要求,需要在Word文檔中添加平鋪水印效果。本文將介紹如何來(lái)實(shí)現(xiàn)該水印效果的方法,感興趣的可以了解一下2022-07-07

