C#鏈接Sql Server的Sql Helper

作爲網上資源最多的一類資料,C#的Sql Helper一搜一大片。不能說某某資料最好,而只能說某某資料最適合自己。在 這兒貼一個我自己的,可以直接用,也可以拿來作爲自己Sql Helper開發的參考。

using System;
using System.Text;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;

namespace SqlHelper {
	public class sqlHelper {
		//管道連接字符串
		private static string strCon = ConfigurationManager.AppSettings["sqlstr"];
		//默認每頁條數
		public const int defPageRow = 40;



		/// <summary>
		/// 獲取Sql管道連接句柄
		/// </summary>
		/// <returns>Sql連接句柄</returns>
		private static SqlConnection GetConn () {
			try {
				SqlConnection conn = null;
				conn = new SqlConnection (strCon);
				conn.Open ();
				return conn;
			} catch (Exception ex) {
				throw ex;
			}
		}



		/// <summary>
		/// 關閉Sql管道連接
		/// </summary>
		/// <param name="conn">管道連接句柄</param>
		private static void Close (SqlConnection conn) {
			try {
				if (conn == null) return;
				if (conn.State == ConnectionState.Open) conn.Close ();
				conn.Dispose ();
			} catch (Exception) {
			}
		}



		/// <summary>
		/// 獲取新參數數組
		/// </summary>
		/// <param name="spc"></param>
		/// <returns></returns>
		private static SqlParameter[] GetNewSqlParameterCollection (SqlParameter[] spc) {
			if (spc == null) return null;
			SqlParameter[] ret = new SqlParameter[spc.Length];
			for (int i = 0; i < spc.Length; i++) {
				ret[i] = new SqlParameter ();
				ret[i].ParameterName = spc[i].ParameterName;
				ret[i].Value = spc[i].Value;
			}
			return ret;
		}



		/// <summary>
		/// ExecuteNonQuery你懂得
		/// </summary>
		/// <param name="strSql"></param>
		/// <param name="spc"></param>
		/// <returns></returns>
		public static int ExecuteNonQuery (string strSql, SqlParameter[] spc) {
			int ret = 0;
			SqlConnection conn = null;
			try {
				conn = GetConn ();
				SqlCommand cmd = new SqlCommand (strSql, conn);
				SqlParameter[] spc2 = GetNewSqlParameterCollection (spc);
				if (spc2 != null) cmd.Parameters.AddRange (spc2);
				ret = cmd.ExecuteNonQuery ();
			} catch (Exception ex) {
				throw ex;
			}
			Close (conn);
			return ret;
		}



		/// <summary>
		/// ExecuteScalary你懂得
		/// </summary>
		/// <param name="strSql"></param>
		/// <param name="spc"></param>
		/// <returns></returns>
		public static object ExecuteScalary (string strSql, SqlParameter[] spc) {
			object ret = null;
			SqlConnection conn = null;
			try {
				conn = GetConn ();
				SqlCommand cmd = new SqlCommand (strSql, conn);
				SqlParameter[] spc2 = GetNewSqlParameterCollection (spc);
				if (spc2 != null) cmd.Parameters.AddRange (spc2);
				ret = cmd.ExecuteScalar ();
			} catch (Exception ex) {
				throw ex;
			}
			Close (conn);
			return ret;
		}



		/// <summary>
		/// ExecuteDataTable你懂得
		/// </summary>
		/// <param name="strSql"></param>
		/// <param name="spc"></param>
		/// <returns></returns>
		public static DataTable ExecuteDataTable (string strSql, SqlParameter[] spc) {
			DataTable ret = null;
			SqlConnection conn = null;
			try {
				conn = GetConn ();
				SqlCommand cmd = new SqlCommand (strSql, conn);
				SqlParameter[] spc2 = GetNewSqlParameterCollection (spc);
				if (spc2 != null) cmd.Parameters.AddRange (spc2);
				DataSet ds = new DataSet ();
				SqlDataAdapter sda = new SqlDataAdapter (cmd);
				sda.Fill (ds);
				ret = ds.Tables[0];
			} catch (Exception ex) {
				throw ex;
			}
			Close (conn);
			return ret;
		}



		/// <summary>
		/// ExecuteDataSet你懂得
		/// </summary>
		/// <param name="strSql"></param>
		/// <param name="spc"></param>
		/// <returns></returns>
		public static DataSet ExecuteDataSet (string strSql, SqlParameter[] spc) {
			DataSet ds = new DataSet ();
			SqlConnection conn = null;
			try {
				conn = GetConn ();
				SqlCommand cmd = new SqlCommand (strSql, conn);
				SqlParameter[] spc2 = GetNewSqlParameterCollection (spc);
				if (spc2 != null) cmd.Parameters.AddRange (spc2);
				SqlDataAdapter sda = new SqlDataAdapter (cmd);
				sda.Fill (ds);
			} catch (Exception ex) {
				throw ex;
			}
			Close (conn);
			return ds;
		}



		/// <summary>
		/// 獲取某錶行數
		/// </summary>
		/// <param name="table">表名(可附加條件)</param>
		/// <param name="spc">參數</param>
		/// <returns>行數</returns>
		public static int GetCount (string table, SqlParameter[] spc = null) {
			return sqlHelper.ExecuteScalary (string.Format ("select count(*) from {0}", table), spc).toInt32 ();
		}



		/// <summary>
		/// 獲取多張表函數總和
		/// </summary>
		/// <param name="spc">參數</param>
		/// <param name="table">表名(可附加條件)</param>
		/// <returns>行數</returns>
		public static int GetCountTotal (SqlParameter[] spc, params string[] table) {
			return sqlHelper.ExecuteScalary(string.Format("select (select count(*) from {0})", table.join(") + (select count(*) from ")), spc).toInt32();
		}



		/// <summary>
		/// 獲取某表查詢時的頁數
		/// </summary>
		/// <param name="table">表名</param>
		/// <param name="pageRow">每頁行數</param>
		/// <returns></returns>
		public static int GetPageCount (string table, int pageRow = -1) {
			try {
				if (pageRow == -1) pageRow = sqlHelper.defPageRow;
				int count = GetCount (table);
				return count / pageRow + (count % pageRow > 0 ? 1 : 0);
			} catch (Exception) {
				return 1;
			}
		}



		/// <summary>
		/// 檢查頁碼是否正確
		/// </summary>
		/// <param name="table">表名</param>
		/// <param name="page">頁碼</param>
		/// <param name="pageRow">每頁條數</param>
		/// <returns>正確的頁碼</returns>
		public static int CheckPage (string table, int page, int pageRow = -1) {
			try {
				int count = sqlHelper.GetPageCount (table, pageRow);
				if (page < 1) return 1;
				if (page > count) return count;
				return page;
			} catch (Exception) {
				return 1;
			}
		}



		/// <summary>
		/// 獲取新ID
		/// </summary>
		/// <returns></returns>
		public static string GetNewID () {
			return sqlHelper.ExecuteScalary ("select newid()", null).ToString ();
		}



		/// <summary>
		/// 獲取參數
		/// </summary>
		/// <param name="s"></param>
		/// <returns></returns>
		public static SqlParameter[] GetParameter (params string[] s) {
			if (s.Length == 0) {
				return null;
			} else if (s.Length % 2 > 0) {
				throw new Exception ("參數個數不可爲奇數!");
			}
			int count = s.Length / 2;
			SqlParameter[] spc = new SqlParameter[count];
			for (int i = 0; i < count; i++) {
				if (s[i * 2][0] != '@') {
					throw new Exception ("參數名命名規則錯誤!");
				}
				spc[i] = new SqlParameter ();
				spc[i].ParameterName = s[i * 2];
				spc[i].Value = s[i * 2 + 1];
			}
			return spc;
		}



		/// <summary>
		/// 獲取某列表
		/// </summary>
		/// <param name="sqlstr">數據庫語句</param>
		/// <param name="spc">數據庫參數</param>
		/// <returns>列表數組</returns>
		public static string[] sGlobalGetList (string sqlstr, SqlParameter[] spc) {
			DataTable dt = sqlHelper.ExecuteDataTable (sqlstr, spc);
			if (dt.Rows.Count == 0) return null;
			string[] sc = new string[dt.Rows.Count];
			StringBuilder sb;
			for (int i = 0; i < dt.Rows.Count; i++) {
				sb = new StringBuilder ();
				for (int j = 0; j < dt.Columns.Count; j++) {
					if (j != 0)
						sb.Append ("#");
					//sb.Append(dt.Rows[i][j].ToString());
					try {
						if (dt.Columns[j].DataType.ToString ().Trim () == "DateTime") {
							sb.Append (Convert.ToDateTime (dt.Rows[i][j]).ToString ("yyyy-MM-dd"));
						} else {
							sb.Append (dt.Rows[i][j].ToString ().Trim ());
						}
					} catch (Exception) { }
				}
				sc[i] = sb.ToString ();
			}
			return sc;
		}



		/// <summary>
		/// 獲取帶標題某列表(一行)
		/// </summary>
		/// <param name="sqlstr">數據庫語句</param>
		/// <param name="spc">數據庫參數</param>
		/// <returns>列表數組</returns>
		public static string[][] hGlobalGetList (string sqlstr, SqlParameter[] spc) {
			try {
				DataTable dt = sqlHelper.ExecuteDataTable (sqlstr, spc);
				string[][] s = new string[2][];
				s[0] = new string[dt.Columns.Count];
				s[1] = new string[dt.Columns.Count];
				for (int i = 0; i < dt.Columns.Count; i++) {
					s[0][i] = dt.Columns[i].ColumnName;
					try {
						if (dt.Columns[i].DataType.ToString ().Trim () == "DateTime") {
							s[1][i] = Convert.ToDateTime (dt.Rows[0][i]).ToString ("yyyy-MM-dd");
						} else {
							s[1][i] = dt.Rows[0][i].ToString ().Trim ();
						}
					} catch (Exception) {
						s[1][i] = "";
					}
				}
				return s;
			} catch (Exception) {
				return null;
			}
		}



		/// <summary>
		/// 獲取完整某表
		/// </summary>
		/// <param name="sqlstr">數據庫語句</param>
		/// <param name="spc">數據庫參數</param>
		/// <returns>二維列表數組</returns>
		public static string[][] mGlobalGetList (string sqlstr, SqlParameter[] spc) {
			try {
				DataTable dt = sqlHelper.ExecuteDataTable (sqlstr, spc);
				string[][] s = new string[dt.Rows.Count][];
				for (int i = 0; i < dt.Rows.Count; i++) {
					s[i] = new string[dt.Columns.Count];
					for (int j = 0; j < dt.Columns.Count; j++) {
						string t = dt.Columns[j].DataType.ToString ().Trim ();
						if (t.IndexOf ('.') >= 0) {
							t = t.Substring (t.LastIndexOf ('.') + 1);
						}
						try {
							if (t == "DateTime") {
								s[i][j] = Convert.ToDateTime (dt.Rows[i][j]).ToString ("yyyy-MM-dd");
							} else {
								s[i][j] = dt.Rows[i][j].ToString ().Trim ();
							}
						} catch (Exception) {
							s[i][j] = "";
						}
					}
				}
				return s;
			} catch (Exception) {
				return null;
			}
		}



		/// <summary>
		/// 返回DataReader數據集
		/// </summary>
		/// <param name="strSql">執行字符串</param>
		/// <returns>DataReader</returns>
		public static SqlDataReader backDataReader (string strSql) {
			SqlDataReader dataReader = null;
			SqlConnection conn = null;
			try {
				conn = GetConn ();
				SqlCommand cmd = new SqlCommand (strSql, conn);
				dataReader = cmd.ExecuteReader (CommandBehavior.CloseConnection);
			} catch (Exception ex) {
				throw ex;
			}
			return dataReader;
		}
	}
}


我這個的功能除了傳統的EexcuteDataTable、ExecuteNonQuery、ExecuteScalary外,還加入了幾個常用功能:

GetPageCount用於獲取某張表的頁數(分頁時用到);

CheckPage用來檢查調用的頁碼是否正確,如果不正確返回1,正確就直接返回頁碼;

sGlobalGetList用來獲取單列的一串,轉爲string[],多列的話就通過#號分隔(比如某行的兩列分別爲 abc 和 def,則字符串爲 abc#def)

hGlobalGetList用來獲取一行,但返回的數據包括列名。這個在數據庫查詢語句中通過類似“select 'XX列' = table.column, 'XX列2' = table.column2”這樣來實現。
mGlobalGetList返回一個二維數組,就是查詢出來的表的結構。這個和sGlobalGetList查詢多列時有相似之處,只不過這個是二位數組而sGlobalGetList通過逗號分隔。

較上次新增一個功能,GetParameter,用於簡潔的獲取sql參數。

調用方式示例:sqlHelper.ExecuteNonQuery("insert into xxx values(@name)", sqlHelper.GetParameter("@name", "name string"));

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章