文章系统图片系统下载系统个人求职企业招聘房产系统展会系统供求系统产品系统商城系统自定义系统后台一览
解决方案
建站知识
.NET三层架构解析:SQLHelper设计
来源:网络作者:网络
public void RunSQL(string cmdText, SqlParameter[] prams, ref DataSet dataSet)
       {
           if (dataSet == null)
           {
               dataSet = new DataSet();
           }
           ///创建SqlDataAdapter
           SqlDataAdapter da = CreateProcDataAdapter(cmdText, prams);
 
           try
           {
               ///读取数据
               da.Fill(dataSet);
           }
           catch (Exception ex)
           {
               ///记录错误日志
               SystemError.CreateErrorLog(ex.Message);
           }
           finally
           {
               ///关闭数据库的连接
               Close();
           }
       }

执行传入参数SQL语句和表名返回DataSet

public void RunSQL(string cmdText, SqlParameter[] prams, string TableName, ref DataSet dataSet)
       {
           if (dataSet == null)
           {
               dataSet = new DataSet();
           }
           ///创建SqlDataAdapter
           SqlDataAdapter da = CreateProcDataAdapter(cmdText, prams);
 
           try
           {
               ///读取数据
               da.Fill(dataSet, TableName);
           }
           catch (Exception ex)
           {
               ///记录错误日志
               SystemError.CreateErrorLog(ex.Message);
           }
           finally
           {
               ///关闭数据库的连接
               Close();
           }
       }

创建一个SqlCommand对象以此来执行存储过程

private SqlCommand CreateProcCommand(string procName, SqlParameter[] prams)
       {
           ///打开数据库连接
           Open();
 
           ///设置Command
           SqlCommand cmd = new SqlCommand(procName, myConnection);
           cmd.CommandType = CommandType.StoredProcedure;
 
 
           ///添加把存储过程的参数
           if (prams != null)
           {
               foreach (SqlParameter parameter in prams)
               {
                   cmd.Parameters.Add(parameter);
               }
           }
 
           ///添加返回参数ReturnValue
           cmd.Parameters.Add(
               new SqlParameter(RETURNVALUE, SqlDbType.Int, 4, ParameterDirection.ReturnValue,
               false, 0, 0, string.Empty, DataRowVersion.Default, null));
 
           ///返回创建的SqlCommand对象
           return cmd;
       }

创建一个SqlCommand对象以此来执行存储过程

private SqlCommand CreateSQLCommand(string cmdText, SqlParameter[] prams)
       {
           ///打开数据库连接
           Open();
 
           ///设置Command
           SqlCommand cmd = new SqlCommand(cmdText, myConnection);
 
           ///添加把存储过程的参数
           if (prams != null)
           {
               foreach (SqlParameter parameter in prams)
               {
                   cmd.Parameters.Add(parameter);
               }
           }
 
           ///添加返回参数ReturnValue
           cmd.Parameters.Add(
               new SqlParameter(RETURNVALUE, SqlDbType.Int, 4, ParameterDirection.ReturnValue,
               false, 0, 0, string.Empty, DataRowVersion.Default, null));
 
           ///返回创建的SqlCommand对象
           return cmd;
       }

创建一个SqlDataAdapter对象,用此来执行存储过程

private SqlDataAdapter CreateProcDataAdapter(string procName, SqlParameter[] prams)
        {
            ///打开数据库连接
            Open();
  
            ///设置SqlDataAdapter对象
            SqlDataAdapter da = new SqlDataAdapter(procName, myConnection);
            da.SelectCommand.CommandType = CommandType.StoredProcedure;
  
            ///添加把存储过程的参数
            if (prams != null)
            {
                foreach (SqlParameter parameter in prams)
                {
                    da.SelectCommand.Parameters.Add(parameter);
                }
            }
  
            ///添加返回参数ReturnValue
            da.SelectCommand.Parameters.Add(
                new SqlParameter(RETURNVALUE, SqlDbType.Int, 4, ParameterDirection.ReturnValue,
                false, 0, 0, string.Empty, DataRowVersion.Default, null));
  
            ///返回创建的SqlDataAdapter对象
            return da;
        }

创建一个SqlDataAdapter对象,用此来执行SQL语句

private SqlDataAdapter CreateSQLDataAdapter(string cmdText, SqlParameter[] prams)
        {
            ///打开数据库连接
            Open();
  
            ///设置SqlDataAdapter对象
            SqlDataAdapter da = new SqlDataAdapter(cmdText, myConnection);
  
            ///添加把存储过程的参数
            if (prams != null)
            {
                foreach (SqlParameter parameter in prams)
                {
                    da.SelectCommand.Parameters.Add(parameter);
                }
            }
  
            ///添加返回参数ReturnValue
            da.SelectCommand.Parameters.Add(
                new SqlParameter(RETURNVALUE, SqlDbType.Int, 4, ParameterDirection.ReturnValue,
                false, 0, 0, string.Empty, DataRowVersion.Default, null));
  
            ///返回创建的SqlDataAdapter对象
            return da;
        }

生成存储过程参数

public SqlParameter CreateParam(string ParamName, SqlDbType DbType, Int32 Size, ParameterDirection Direction, object Value)
       {
           SqlParameter param;
 
           ///当参数大小为0时,不使用该参数大小值
           if (Size > 0)
           {
               param = new SqlParameter(ParamName, DbType, Size);
           }
           else
           {
               ///当参数大小为0时,不使用该参数大小值
               param = new SqlParameter(ParamName, DbType);
           }
 
           ///创建输出类型的参数
           param.Direction = Direction;
           if (!(Direction == ParameterDirection.Output && Value == null))
           {
               param.Value = Value;
           }
 
           ///返回创建的参数
           return param;
       }

传入输入参数

public SqlParameter CreateInParam(string ParamName, SqlDbType DbType, int Size, object Value)
{
    return CreateParam(ParamName, DbType, Size, ParameterDirection.Input, Value);
}

传入返回值参数

public SqlParameter CreateOutParam(string ParamName, SqlDbType DbType, int Size)
{
    return CreateParam(ParamName, DbType, Size, ParameterDirection.Output, null);
}

传入返回值参数

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>
       /// 包含系统Excepton
       /// </summary>
       public SystemException(string source, string message, Exception inner)
           : base(message, inner)
       {
           base.Source = source;
       }
 
       /// <summary>
       /// 不包含系统Excepton
       /// </summary>            
       public SystemException(string source, string message)
           : base(message)
       {
           base.Source = source;
       }
   }
 
   /// <summary>
   /// 处理网页中的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转为DataTable
       /// </summary>
       /// <param name="DataReader">DataReader</param>
       public static DataTable ConvertDataReaderToDataTable(SqlDataReader dataReader)
       {
           ///定义DataTable
           DataTable datatable = new DataTable();
 
           try
           {   ///动态添加表的数据列
               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);
               }
 
               ///添加表的数据
               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;
               }
               ///关闭数据读取器
               dataReader.Close();
               return datatable;
           }
           catch (Exception ex)
           {
               ///抛出类型转换错误
               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))
        {
            ///如果日志文件已经存在,则直接写入日志文件
            StreamWriter sr = File.AppendText(FileName);
            sr.WriteLine("\n");
            sr.WriteLine(DateTime.Now.ToString() + message);
            sr.Close();
        }
        else
        {
            ///创建日志文件
            StreamWriter sr = File.CreateText(FileName);
            sr.Close();
        }   
    }
}