您的位置:首页 > 数据库

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

2006-09-20 06:32 507 查看
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);

}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: