整理數據庫操作類以便取用:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data; using System.Data.SqlClient; using System.Configuration; namespace Eshop { public class DbManage { #region 類中的全局變量-數據連接字符串 public static string strcon = ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString.ToString();//連接字符串,使用Windows登錄方式 #endregion #region 構造函數 /// <summary> /// 構造函數,初始化時連接數據庫 /// </summary> public DbManage() { strcon = ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString.ToString(); } #endregion #region 返回SqlDataReader-ExceRead類型的數據 /// <summary> /// 此方法返回SqlDataReader-ExceRead類型的參數 /// </summary> /// <param name="Sqlcom"></param> /// <returns></returns> public static SqlDataReader ExceRead(string Sqlcom) { SqlConnection con = new SqlConnection(strcon); try { con.Open(); SqlCommand com = new SqlCommand(Sqlcom,con); SqlDataReader read = com.ExecuteReader(); return read; } catch (SqlException E) { throw new Exception(E.Message); } } #endregion #region 返回SqlDataReader-ExceScalar類型的數據 /// <summary> /// 此方法返回SqlDataReader-ExceScalar類型的參數 /// </summary> /// <param name="Sqlcom"></param> /// <returns></returns> public static object ExceScalar(string Sqlcom) { SqlConnection con = new SqlConnection(strcon); try { con.Open(); SqlCommand com = new SqlCommand(Sqlcom, con); object strdata = com.ExecuteScalar(); return strdata; } catch (SqlException E) { throw new Exception(E.Message); } } #endregion #region 返回DataSet類型的數據並獲得tableName參數 /// <summary> /// 此方法返回一個DataSet類型 /// </summary> /// <param name="strsql">要執行的SQL語句</param> /// <param name="tablename"></param> /// <returns></returns> public static DataSet GetDataSet(string strsql,string tablename) { //定義一個數據集,用來賦值給應用程序的一個數據集 SqlConnection con = new SqlConnection(strcon); DataSet ds = new DataSet(); try { SqlDataAdapter DA = new SqlDataAdapter(strsql,con); DA.Fill(ds,tablename); } catch (SqlException E) { throw new Exception(E.Message); } return ds; } #endregion #region 執行SQL語句,包括增刪改 /// <summary> /// 此方法用來執行SQL語句 /// </summary> /// <param name="strSqlCom">要執行的SQL語句</param> /// <returns></returns> public static bool ExceSQL(string strSqlCom) { SqlConnection con = new SqlConnection(strcon); SqlCommand com = new SqlCommand(strSqlCom,con); try { //判斷數據庫是否為連接狀態 if (con.State == ConnectionState.Closed) { con.Open(); } //執行SQL語句 com.ExecuteNonQuery(); //SQL語句執行成功,返回true值 return true; } catch { //SQL語句執行失敗,返回false值 return false; } finally { //關閉數據庫連接 con.Close(); } } #endregion } }