步步為營 .NET三層架構(gòu)解析 三、SQLHelper設計 文章錄入:7747.Net 責任編輯:7747.Net 29 【字體:小 大】 數(shù)據(jù)庫設計好了,我們開始設計SQLHelper了,是一個SQL基類.
連接數(shù)據(jù)源:
private SqlConnection myConnection = null; private readonly string RETURNVALUE = "RETURNVALUE";
打開數(shù)據(jù)庫連接.
private void Open() { // 打開數(shù)據(jù)庫連接 if (myConnection == null) { // myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString); myConnection = new SqlConnection(ConfigurationManager.AppSettings["ConnectionString"].ToString()); } if (myConnection.State == ConnectionState.Closed) { try { ///打開數(shù)據(jù)庫連接 myConnection.Open(); } catch (Exception ex) { SystemError.CreateErrorLog(ex.Message); } finally { ///關(guān)閉已經(jīng)打開的數(shù)據(jù)庫連接 } } }
關(guān)閉數(shù)據(jù)庫連接
public void Close() { ///判斷連接是否已經(jīng)創(chuàng)建 if (myConnection != null) { ///判斷連接的狀態(tài)是否打開 if (myConnection.State == ConnectionState.Open) { myConnection.Close(); } } }
釋放資源
public void Dispose() { // 確認連接是否已經(jīng)關(guān)閉 if (myConnection != null) { myConnection.Dispose(); myConnection = null; } }
執(zhí)行無參數(shù)和返回int型的存儲過程
public int RunProc(string procName) { SqlCommand cmd = CreateProcCommand(procName, null); try { ///執(zhí)行存儲過程 cmd.ExecuteNonQuery(); } catch (Exception ex) { ///記錄錯誤日志 SystemError.CreateErrorLog(ex.Message); } finally { ///關(guān)閉數(shù)據(jù)庫的連接 Close(); }
///返回存儲過程的參數(shù)值 return (int)cmd.Parameters[RETURNVALUE].Value; }
執(zhí)行傳入?yún)?shù)和返回int型的存儲過程
public int RunProc(string procName, SqlParameter[] prams) { SqlCommand cmd = CreateProcCommand(procName, prams); try { ///執(zhí)行存儲過程 cmd.ExecuteNonQuery(); } catch (Exception ex) { ///記錄錯誤日志 SystemError.CreateErrorLog(ex.Message); } finally { ///關(guān)閉數(shù)據(jù)庫的連接 Close(); }
///返回存儲過程的參數(shù)值 return (int)cmd.Parameters[RETURNVALUE].Value; }
執(zhí)行存儲過程和返回SqlDataReader
public void RunProc(string procName, out SqlDataReader dataReader) { ///創(chuàng)建Command SqlCommand cmd = CreateProcCommand(procName, null);
try { ///讀取數(shù)據(jù) dataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection); } catch (Exception ex) { dataReader = null; ///記錄錯誤日志 SystemError.CreateErrorLog(ex.Message); } }
執(zhí)行傳入?yún)?shù)和返回SqlDataReader存儲過程
public void RunProc(string procName, SqlParameter[] prams, out SqlDataReader dataReader) { ///創(chuàng)建Command SqlCommand cmd = CreateProcCommand(procName, prams);
try { ///讀取數(shù)據(jù) dataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection); } catch (Exception ex) { dataReader = null; ///記錄錯誤日志 SystemError.CreateErrorLog(ex.Message); } }
執(zhí)行無參數(shù)存儲過程返回DataSet
public void RunProc(string procName, ref DataSet dataSet) { if (dataSet == null) { dataSet = new DataSet(); } ///創(chuàng)建SqlDataAdapter SqlDataAdapter da = CreateProcDataAdapter(procName, null);
try { ///讀取數(shù)據(jù) da.Fill(dataSet); } catch (Exception ex) { ///記錄錯誤日志 SystemError.CreateErrorLog(ex.Message); } finally { ///關(guān)閉數(shù)據(jù)庫的連接 Close(); } }
執(zhí)行傳入?yún)?shù)的存儲過程返回DataSet
public void RunProc(string procName, SqlParameter[] prams, ref DataSet dataSet) { if (dataSet == null) { dataSet = new DataSet(); } ///創(chuàng)建SqlDataAdapter SqlDataAdapter da = CreateProcDataAdapter(procName, prams);
try { ///讀取數(shù)據(jù) da.Fill(dataSet); } catch (Exception ex) { ///記錄錯誤日志 SystemError.CreateErrorLog(ex.Message); } finally { ///關(guān)閉數(shù)據(jù)庫的連接 Close(); } }
執(zhí)行傳入?yún)?shù)和表名的存儲過程返回DataSet
public void RunProc(string procName, SqlParameter[] prams, string TableName, ref DataSet dataSet) { if (dataSet == null) { dataSet = new DataSet(); } ///創(chuàng)建SqlDataAdapter SqlDataAdapter da = CreateProcDataAdapter(procName, prams);
try { ///讀取數(shù)據(jù) da.Fill(dataSet, TableName); } catch (Exception ex) { ///記錄錯誤日志 SystemError.CreateErrorLog(ex.Message); } finally { ///關(guān)閉數(shù)據(jù)庫的連接 Close(); } }
執(zhí)行無參數(shù)SQL語句
public int RunSQL(string cmdText) { SqlCommand cmd = CreateSQLCommand(cmdText, null); try { ///執(zhí)行存儲過程 cmd.ExecuteNonQuery(); } catch (Exception ex) { ///記錄錯誤日志 SystemError.CreateErrorLog(ex.Message); } finally { ///關(guān)閉數(shù)據(jù)庫的連接 Close(); }
///返回存儲過程的參數(shù)值 return (int)cmd.Parameters[RETURNVALUE].Value; }
執(zhí)行傳入?yún)?shù)SQL語句
public int RunSQL(string cmdText, SqlParameter[] prams) { SqlCommand cmd = CreateSQLCommand(cmdText, prams); try { ///執(zhí)行存儲過程 cmd.ExecuteNonQuery(); } catch (Exception ex) { ///記錄錯誤日志 SystemError.CreateErrorLog(ex.Message); } finally { ///關(guān)閉數(shù)據(jù)庫的連接 Close(); }
///返回存儲過程的參數(shù)值 return (int)cmd.Parameters[RETURNVALUE].Value; }
執(zhí)行無參數(shù)SQL語句返回SqlDataReader
public void RunSQL(string cmdText, out SqlDataReader dataReader) { ///創(chuàng)建Command SqlCommand cmd = CreateSQLCommand(cmdText, null);
try { ///讀取數(shù)據(jù) dataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection); } catch (Exception ex) { dataReader = null; ///記錄錯誤日志 SystemError.CreateErrorLog(ex.Message); } }
執(zhí)行傳入?yún)?shù)SQL語句返回SqlDataReader
public void RunSQL(string cmdText, SqlParameter[] prams, out SqlDataReader dataReader) { ///創(chuàng)建Command SqlCommand cmd = CreateSQLCommand(cmdText, prams);
try { ///讀取數(shù)據(jù) dataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection); } catch (Exception ex) { dataReader = null; ///記錄錯誤日志 SystemError.CreateErrorLog(ex.Message); } }
執(zhí)行無參數(shù)SQL語句返回DataSet
public void RunSQL(string cmdText, ref DataSet dataSet) { if (dataSet == null) { dataSet = new DataSet(); } ///創(chuàng)建SqlDataAdapter SqlDataAdapter da = CreateSQLDataAdapter(cmdText, null);
try { ///讀取數(shù)據(jù) da.Fill(dataSet); } catch (Exception ex) { ///記錄錯誤日志 SystemError.CreateErrorLog(ex.Message); } finally { ///關(guān)閉數(shù)據(jù)庫的連接 Close(); } }
執(zhí)行傳入?yún)?shù)SQL語句返回DataSet
public void RunSQL(string cmdText, SqlParameter[] prams, ref DataSet dataSet) { if (dataSet == null) { dataSet = new DataSet(); } ///創(chuàng)建SqlDataAdapter SqlDataAdapter da = CreateProcDataAdapter(cmdText, prams);
try { ///讀取數(shù)據(jù) da.Fill(dataSet); } catch (Exception ex) { ///記錄錯誤日志 SystemError.CreateErrorLog(ex.Message); } finally { ///關(guān)閉數(shù)據(jù)庫的連接 Close(); } }
執(zhí)行傳入?yún)?shù)SQL語句和表名返回DataSet
public void RunSQL(string cmdText, SqlParameter[] prams, string TableName, ref DataSet dataSet) { if (dataSet == null) { dataSet = new DataSet(); } ///創(chuàng)建SqlDataAdapter SqlDataAdapter da = CreateProcDataAdapter(cmdText, prams);
try { ///讀取數(shù)據(jù) da.Fill(dataSet, TableName); } catch (Exception ex) { ///記錄錯誤日志 SystemError.CreateErrorLog(ex.Message); } finally { ///關(guān)閉數(shù)據(jù)庫的連接 Close(); } }
創(chuàng)建一個SqlCommand對象以此來執(zhí)行存儲過程
private SqlCommand CreateProcCommand(string procName, SqlParameter[] prams) { ///打開數(shù)據(jù)庫連接 Open();
///設置Command SqlCommand cmd = new SqlCommand(procName, myConnection); cmd.CommandType = CommandType.StoredProcedure;
///添加把存儲過程的參數(shù) if (prams != null) { foreach (SqlParameter parameter in prams) { cmd.Parameters.Add(parameter); } }
///添加返回參數(shù)ReturnValue cmd.Parameters.Add( new SqlParameter(RETURNVALUE, SqlDbType.Int, 4, ParameterDirection.ReturnValue, false, 0, 0, string.Empty, DataRowVersion.Default, null));
///返回創(chuàng)建的SqlCommand對象 return cmd; }
創(chuàng)建一個SqlCommand對象以此來執(zhí)行存儲過程
private SqlCommand CreateSQLCommand(string cmdText, SqlParameter[] prams) { ///打開數(shù)據(jù)庫連接 Open();
///設置Command SqlCommand cmd = new SqlCommand(cmdText, myConnection);
///添加把存儲過程的參數(shù) if (prams != null) { foreach (SqlParameter parameter in prams) { cmd.Parameters.Add(parameter); } }
///添加返回參數(shù)ReturnValue cmd.Parameters.Add( new SqlParameter(RETURNVALUE, SqlDbType.Int, 4, ParameterDirection.ReturnValue, false, 0, 0, string.Empty, DataRowVersion.Default, null));
///返回創(chuàng)建的SqlCommand對象 return cmd; }
創(chuàng)建一個SqlDataAdapter對象,,用此來執(zhí)行存儲過程
private SqlDataAdapter CreateProcDataAdapter(string procName, SqlParameter[] prams) { ///打開數(shù)據(jù)庫連接 Open();
///設置SqlDataAdapter對象 SqlDataAdapter da = new SqlDataAdapter(procName, myConnection); da.SelectCommand.CommandType = CommandType.StoredProcedure;
///添加把存儲過程的參數(shù) if (prams != null) { foreach (SqlParameter parameter in prams) { da.SelectCommand.Parameters.Add(parameter); } }
///添加返回參數(shù)ReturnValue da.SelectCommand.Parameters.Add( new SqlParameter(RETURNVALUE, SqlDbType.Int, 4, ParameterDirection.ReturnValue, false, 0, 0, string.Empty, DataRowVersion.Default, null));
///返回創(chuàng)建的SqlDataAdapter對象 return da; }
創(chuàng)建一個SqlDataAdapter對象,用此來執(zhí)行SQL語句
private SqlDataAdapter CreateSQLDataAdapter(string cmdText, SqlParameter[] prams) { ///打開數(shù)據(jù)庫連接 Open();
///設置SqlDataAdapter對象 SqlDataAdapter da = new SqlDataAdapter(cmdText, myConnection);
///添加把存儲過程的參數(shù) if (prams != null) { foreach (SqlParameter parameter in prams) { da.SelectCommand.Parameters.Add(parameter); } }
///添加返回參數(shù)ReturnValue da.SelectCommand.Parameters.Add( new SqlParameter(RETURNVALUE, SqlDbType.Int, 4, ParameterDirection.ReturnValue, false, 0, 0, string.Empty, DataRowVersion.Default, null));
///返回創(chuàng)建的SqlDataAdapter對象 return da; }
生成存儲過程參數(shù)
public SqlParameter CreateParam(string ParamName, SqlDbType DbType, Int32 Size, ParameterDirection Direction, object Value) { SqlParameter param;
///當參數(shù)大小為0時,,不使用該參數(shù)大小值 if (Size > 0) { param = new SqlParameter(ParamName, DbType, Size); } else { ///當參數(shù)大小為0時,,不使用該參數(shù)大小值 param = new SqlParameter(ParamName, DbType); }
///創(chuàng)建輸出類型的參數(shù) param.Direction = Direction; if (!(Direction == ParameterDirection.Output && Value == null)) { param.Value = Value; }
///返回創(chuàng)建的參數(shù) return param; }
傳入輸入?yún)?shù)
public SqlParameter CreateInParam(string ParamName, SqlDbType DbType, int Size, object Value) { return CreateParam(ParamName, DbType, Size, ParameterDirection.Input, Value); }
傳入返回值參數(shù)
public SqlParameter CreateOutParam(string ParamName, SqlDbType DbType, int Size) { return CreateParam(ParamName, DbType, Size, ParameterDirection.Output, null); }
傳入返回值參數(shù)
public SqlParameter CreateReturnParam(string ParamName, SqlDbType DbType, int Size) { return CreateParam(ParamName, DbType, Size, ParameterDirection.ReturnValue, null); }
把所有這些方法放在SQLHelper.cs類里.再建一個SQLTools.cs,里面的方法如下:
public class SystemException : Exception { /// <summary> /// 包含系統(tǒng)Excepton /// </summary> public SystemException(string source, string message, Exception inner) : base(message, inner) { base.Source = source; }
/// <summary> /// 不包含系統(tǒng)Excepton /// </summary> public SystemException(string source, string message) : base(message) { base.Source = source; } }
/// <summary> /// 處理網(wǎng)頁中的HTML代碼,并消除危險字符 /// </summary> public class SystemHTML { private static string HTMLEncode(string fString) { if (fString != string.Empty) { ///替換尖括號 fString.Replace("<", "<"); fString.Replace(">", "&rt;"); ///替換引號 fString.Replace(((char)34).ToString(), """); fString.Replace(((char)39).ToString(), "'"); ///替換空格 fString.Replace(((char)13).ToString(), ""); ///替換換行符 fString.Replace(((char)10).ToString(), "<BR> "); } return (fString); } }
/// <summary> /// SystemTools 的摘要說明,。 /// </summary> public class SystemTools { /// <summary> /// 將DataReader轉(zhuǎn)為DataTable /// </summary> /// <param name="DataReader">DataReader</param> public static DataTable ConvertDataReaderToDataTable(SqlDataReader dataReader) { ///定義DataTable DataTable datatable = new DataTable();
try { ///動態(tài)添加表的數(shù)據(jù)列 for (int i = 0; i < dataReader.FieldCount; i++) { DataColumn myDataColumn = new DataColumn(); myDataColumn.DataType = dataReader.GetFieldType(i); myDataColumn.ColumnName = dataReader.GetName(i); datatable.Columns.Add(myDataColumn); }
///添加表的數(shù)據(jù) while (dataReader.Read()) { DataRow myDataRow = datatable.NewRow(); for (int i = 0; i < dataReader.FieldCount; i++) { myDataRow[i] = dataReader[i].ToString(); } datatable.Rows.Add(myDataRow); myDataRow = null; } ///關(guān)閉數(shù)據(jù)讀取器 dataReader.Close(); return datatable; } catch (Exception ex) { ///拋出類型轉(zhuǎn)換錯誤 SystemError.CreateErrorLog(ex.Message); throw new Exception(ex.Message, ex); } } }
主要是處理異常和一些特殊字符.
再建一個SystemError.cs,里面的方法如下:
public class SystemError { private static string m_fileName = "c:\\Systemlog.txt";
public static String FileName { get { return (m_fileName); } set { if (value != null || value != "") { m_fileName = value; } } } public static void CreateErrorLog(string message) { if (File.Exists(m_fileName)) { ///如果日志文件已經(jīng)存在,,則直接寫入日志文件 StreamWriter sr = File.AppendText(FileName); sr.WriteLine("\n"); sr.WriteLine(DateTime.Now.ToString() + message); sr.Close(); } else { ///創(chuàng)建日志文件 StreamWriter sr = File.CreateText(FileName); sr.Close(); } } }
主要記錄日志.
我們的SQLHelper類就建完了,接下來我們就開始建Model類了.歡迎拍磚
摘自紅色黑客聯(lián)盟(www.) 原文:http://www./kf/201103/86546.html
|