C#操作Access之读取mdb

转载来自http://blog.csdn.net/chelen_jak/article/details/65629418

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

        private class MDBHelp  
        {  
            private string _fileName;  
            private string _connectionString;  
            private OleDbConnection _odcConnection;  


            ///   
            /// 构建函数  
            ///   
            /// MDB文件(含完整路徑)  
            public MDBHelp(string fileName)  
            {  
                this._fileName = fileName;  
                this._connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileName + ";";  
            }  


            ///   
            /// 建立连接(打开数据库文件)  
            ///   
            public void Open()  
            {  
                try  
                {  
                    // 建立连接  
                    this._odcConnection = new OleDbConnection(this._connectionString);  


                    // 打开连接  
                    this._odcConnection.Open();  
                }  
                catch (Exception)  
                {  
                    throw new Exception("嘗試打开 " + this._fileName + " 失敗, 請確認文件是否存在!");  
                }  
            }  


            ///   
            /// 断开连接(关闭据库文件)  
            ///   
            public void Close()  
            {  
                this._odcConnection.Close();  
            }  


            ///   
            /// 根据sql命令返回一个DataSet  
            ///   
            /// sql命令  
            /// 以DataTable形式返回数据  
            public DataSet GetDataSet(string sql)  
            {  
                DataSet ds = new DataSet();  


                try  
                {  
                    OleDbDataAdapter adapter = new OleDbDataAdapter(sql, this._odcConnection);  
                    adapter.Fill(ds);  
                }  
                catch (Exception)  
                {  
                    throw new Exception("sql語句: " + sql + " 執行失敗!");  
                }  


                return ds;  
            }  
        }     

调用方法

string mdbFile = "p:\\EvenYYMM.mdb";           //默認路徑  

MDBHelp mdbHelp = new MDBHelp(mdbFile);  
try  
{  
    mdbHelp.Open();     // 打開數據庫  

    var ds1 = mdbHelp.GetDataSet("select count(*) as n1 from even where id > " + last_id.ToString());  

    var ds = mdbHelp.GetDataSet("select to 10 * from even where Id >= 100 order by id");  

    mdbHelp.Close();    // 關閉數據庫  
}  
finally  
{  
    mdbHelp = null;  
}  

你可能感兴趣的:(C#)