现在的位置: 首页 > 综合 > 正文

C#编写的OleDb数据库连接通用类库

2013年06月13日 ⁄ 综合 ⁄ 共 2258字 ⁄ 字号 评论关闭

ADOHelper.cs

using System;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
using System.Data.OleDb;
using IBMDADB2Lib;
using HR1930.COM.Util;

namespace HR1930.COM.DB
{
 /// <summary>
 /// Summary description for ADOHelper.
 /// </summary>
 public class ADOHelper
 {
  
  // private member variables
  OleDbConnection con;    
  static String m_ConnectionString;

  public ADOHelper()
  {
   con = new OleDbConnection(ADOHelper.ConnectionString());
  
  }
  public DataSet ExecuteGet(string cmd)
  {
   this.CheckConnection();
   
   DataSet dataSet = new DataSet();

   try
   {
    OleDbCommand dataCommand = new OleDbCommand(cmd,con);
    OleDbDataAdapter dataAdapter = new OleDbDataAdapter();
    dataAdapter.SelectCommand = dataCommand;
      
    dataAdapter.Fill(dataSet, "recordSet");
       
   }
   catch(SqlException se)
   {
    ErrorLog el = new ErrorLog(se);
    throw new Exception("Error in SQL", se);
   }
   this.Dispose();
   return dataSet;
  }
  public OleDbDataReader ExecuteRead(String cmd)
  {
   this.CheckConnection();

   OleDbDataReader dr = null;
   
   try
   {
    OleDbCommand dc = new OleDbCommand(cmd, con);
    dr = dc.ExecuteReader();
    return dr;
   }
   catch(SqlException se)
   {
    ErrorLog el = new ErrorLog(se);
   }
   this.Dispose();
   return dr;
  }
  public void ExecuteUpdate(string cmd)
  {
   this.CheckConnection();
   try
   {
    OleDbCommand dc = new OleDbCommand(cmd, con);
    dc.ExecuteNonQuery();
   }
   catch(SqlException se)
   {
    ErrorLog el = new ErrorLog(se);
   }
   this.Dispose();
   return;    
  }
  private void CheckConnection()
  {
   try
   {
    if (con.State != ConnectionState.Open)
     con.Open();
   }
   catch (System.Data.SqlClient.SqlException se)
   {
    ErrorLog el = new ErrorLog(se);
    throw new Exception("Failed to Open connection.", se);
   }
  }
  public static String ConnectionString()
  {
   // Pull the ConnectionString from the ASP+ AppSettings section.
   // Cache in static field for faster repeat access.
   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();
    //con = null;
   }
   catch(Exception e)
   {
    ErrorLog el = new ErrorLog(e);
    
   }
  }
 }
}

 

抱歉!评论已关闭.