发布一个数据操作底层类

时间:2021-10-29 10:03:06

我对这个类不是很满意,如果你有改进意见请联系我,不胜感激.

主要将对数据库的操作简单封装了一下

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Configuration;
using System.Data.SqlClient;

namespace Addr.Admin.ExecuteSqlCommand
{
 ///
 /// ExecuteCommand 的摘要说明:数据处理层。
 ///
 public class ExecuteCommand
 {
  string cnStr;
  string errorMessage="";
  bool successful=true;
  //构造函数将连接字符串赋给变量
  public ExecuteCommand()
  {
   //
   // TODO: 在此处添加构造函数逻辑
   //
   cnStr=ConfigurationSettings.AppSettings["cn"];
  }
  //枚举执行sqlcommand的类型
  public enum cmdType
  {
   ExecuteNonQuery=1,
   ExecuteScalar,
   ExecuteReader,
   ExecuteDataSet,
   ExecuteID
  };
  //返回是否执行成功的属性
  public bool rlt
  {
   get
   {
    return successful;
   }
  }
  //返回错误信息
  public string msg
  {
   get
   {
    return errorMessage;
   }
  }
  //执行命令的函数
  public object Executing(SqlCommand cm,cmdType type)
  {
   SqlConnection cn;
   try
   {
    cn=new SqlConnection(cnStr);
    cn.Open();
    cm.Connection=cn;

    switch(type)
    {
     case cmdType.ExecuteNonQuery:
      try
      {
       cm.ExecuteNonQuery();
       cn.Close();
      }
      catch(Exception ex)
      {
       errorMessage="Error executing 'ExecuteNonQuery'."+ex.Message;
       successful=false;
      }
      break;
     case cmdType.ExecuteReader:
      try
      {
       SqlDataAdapter da=new SqlDataAdapter(cm.CommandText,cn);
       DataSet ds=new DataSet();
       da.Fill(ds,"First");
       da.Dispose();
       cn.Close();
       return ds.Tables["First"];
      }
      catch
      {
       errorMessage="Error executing 'ExecuteReader'.";
       successful=false;
      }
      break;
     case cmdType.ExecuteScalar:
      try
      {
       int result=(int)cm.ExecuteScalar();
       cn.Close();
       return result;
      }
      catch
      {
       errorMessage="Error executing 'ExecuteScalar'.'";
       successful=false;
      }
      break;
     case cmdType.ExecuteDataSet:
      try
      {
       SqlDataAdapter da=new SqlDataAdapter(cm.CommandText,cn);
       DataSet ds=new DataSet();
       da.Fill(ds);
       cn.Close();
       return ds;
      }
      catch
      {
       errorMessage="Error executing 'ExecuteDataSet'.";
       successful=false;
      }
      break;
     case cmdType.ExecuteID:
      try
      {
       string rst="";
       SqlDataReader dr=cm.ExecuteReader();
       if(dr.Read())
       {
        rst=dr["ID"].ToString();
       }
       dr.Close();
       cn.Close();
       return rst;
      }
      catch
      {
       errorMessage="Error executing 'ExecuteID'.";
       successful=false;
      }
      break;
     default:
      errorMessage="Error executing unknown sqlcommand.";
      successful=false;
      break;
    }
    return successful;
   }
   catch
   {
    successful=false;
    errorMessage="Error opening data connection.";
    return successful;
   }
  }
 }
}