一个不完整的OLEDB操作类(自己乱写的,呵呵)

其实功能很简单,而且局限性很大

首先没有加入DATASET的操作,其次,这个类只能连接ACCESS数据库,呵呵,见笑了。

using  System;
using  System.Data;
using  System.Data.OleDb;

namespace  dbControlDemo
{

    
public class dbControl
    
{
        
private string _database;
        
public string DataBase()//返回数据库名称
        {
            
return this._database;
        }


        OleDbConnection Conn;

        
public dbControl(string DataBase)
        
{
            
//
            
// TODO: 在此处添加构造函数逻辑
            
//
            this._database = DataBase;
            Conn 
= new OleDbConnection();
            Conn.ConnectionString 
= "Provider = Microsoft.Jet.OLEDB.4.0;Data Source ="+this._database;
        }


        
//返回DataReader
        public OleDbDataReader getDataReader(string sql)
        
{
            
this.CheckConnection();
            OleDbDataReader dr 
= null;

            
try
            
{
                OleDbCommand dc 
= new OleDbCommand(sql,Conn);        
                dr 
= dc.ExecuteReader();    
            }

            
catch(OleDbException oe)
            
{
                
throw new Exception("您在执行Sql语句:"+sql.ToString()+"发生异常。读取数据库出现错误!",oe);
            }

            
return dr;
            
this.Close();
        }


        
//没有返回值,执行数据库操作
        public void Execute(string sql)
        
{
            
this.CheckConnection();
            
try
            
{
                OleDbCommand dc 
= new OleDbCommand(sql,Conn);
                dc.ExecuteNonQuery();
            }

            
catch(OleDbException oe)
            
{
                
throw new Exception("您在执行Sql语句:"+sql.ToString()+"发生异常。执行数据库操作出现错误!",oe);
            }

            
this.Close();
        }


        
private void CheckConnection()
        
{
            
try
            
{
                
if (Conn.State != ConnectionState.Open)
                    Conn.Open();
            }

            
catch (OleDbException oe)
            
{
                
throw new Exception("打开数据库联接错误!", oe);
            }

        }

        
public void Close()
        
{
            
try
            
{
                
if (Conn.State == ConnectionState.Open)
                
{
                    Conn.Close();
                }

            }

            
catch(Exception e){
                
throw new Exception("数据库关闭错误!",e);
            }

        }


    }

}


还请大家猛烈的拍砖,看看什么地方做得不合理的,请告诉我,谢谢阿~

你可能感兴趣的:(DB)