C编写的SQL Server 数据库连接通用类库

时间:2022-06-01 04:26:31

public class ADOHelper
 {
  private SqlConnection con;
  static string m_ConnectionString;
  public ADOHelper()
  {
   con=new SqlConnection(ADOHelper.ConnectionString());
  }
  public static string ConnectionString()
  {
   if(m_ConnectionString==null)
   {
    m_ConnectionString=(string)ConfigurationSettings.AppSettings["ConnectionString"];
    if(m_ConnectionString==null)
    {
     throw new Exception("Connect string value not set in web.config");
    }
   }
   return m_ConnectionString;
  }

  public void Dispose()
  {
   try
   {
    if(con.State==ConnectionState.Open)
     con.Close();
   }
   catch
   {
    throw new Exception ("ConnectionState faile");
   }
  }

  private void CheckConnection()
  {
   try
   {
    if(con.State!=ConnectionState.Open)
     con.Open();
   }
   catch
   {
    throw new Exception("Failed to open connection");
   }
  }

  public DataSet ExecuteGet(string cmd)
  {
   this.CheckConnection();
   DataSet dataSet =new DataSet();
   try
   {
    SqlCommand dataCommand =new SqlCommand(cmd,con);
    SqlDataAdapter dataAdapter=new SqlDataAdapter();
    dataAdapter.SelectCommand=dataCommand;
    dataAdapter.Fill(dataSet,"recordSet");

   }
   catch
   {
    throw new Exception("Error in SQL");
   }
   this.Dispose();
   return dataSet;
  }

  public SqlDataReader ExecuteRead(string cmd)
  {
   this.CheckConnection();
   SqlDataReader dr=null;
   try
   {
    SqlCommand dc=new SqlCommand(cmd,con);
    dr=dc.ExecuteReader();
   }
   catch
   {
    throw new Exception("Failed!");
   }
   this.Dispose();
   return dr;
  }

  public void ExecuteUpdate(string cmd)
  {
   this.CheckConnection();
   try
   {
    SqlCommand dc = new SqlCommand(cmd,con);
    dc.ExecuteNonQuery();
   }
   catch
   {
    throw new Exception("failed!");
   }
   this.Dispose();
   return;
  }