using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.UI;
using System.Data.OleDb;

namespace Solog.AcessTask
{
    
/// <summary>
    
/// 数据操作层辅助类
    
/// 提供数据源,SQL操作
    
/// </summary>


    
public class GetData:System.Web.UI.Page
    
{
        
private OleDbConnection  _myConn;
        
private static string dbpath =HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["dbpath"]);

        
public GetData()
        
{
            
string ConnectString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + dbpath;
            _myConn 
= new OleDbConnection(ConnectString);
 
        }

       
        
public OleDbConnection MyConn()
        
{
            
try 
            
{
                _myConn.Open();
            }

            
catch(System.Data.OleDb.OleDbException e)
            
{
                
throw new Exception(e.Message);
            }

            
return _myConn;
           
        }

        
public void closeConn()
        
{
            _myConn.Close();
        }


        
public DataSet GetDataset(string sql)
        
{
            
//获取DataSet
            DataSet ds =new DataSet();
            
try
            
{
                OleDbDataAdapter dap 
= new OleDbDataAdapter(sql,this.MyConn());
                dap.Fill(ds);
                
return ds;
            }

            
catch (System.Data.OleDb.OleDbException e)
            
{
                
throw new Exception(e.Message);
            }

            
finally
            
{
                closeConn();
            }

        }


        
/// <summary>
        
/// 获取OleDataReader
        
/// </summary>
        
/// <param name="sqlstring">SQL语句</param>
        
/// <returns>OleDataReader</returns>

        public OleDbDataReader GetReader(string sqlstring)
        
{
            
//获取IDataReader
            OleDbDataReader datareader = null;
            OleDbCommand dbcmd 
= new OleDbCommand(sqlstring,this.MyConn());

            
try
            
{
                datareader 
= dbcmd.ExecuteReader(CommandBehavior.CloseConnection);
                
return datareader;
            }

            
catch (System.Data.OleDb.OleDbException e)
            
{
                
throw new Exception(e.Message);
            }

            
        }

        
public  void excNonQuery(string sqlstring)
        
{
            
//执行一个无返回值的COMMADND
            OleDbCommand exc = new OleDbCommand(sqlstring,this.MyConn());
            exc.ExecuteNonQuery();
            exc.Connection.Close();
        }

        
public int excScalar(string sqlstring)
        
{
            
//执行返回单一INT值
            OleDbCommand exc = new OleDbCommand(sqlstring, this.MyConn());
            
int result = Convert.ToInt32(exc.ExecuteScalar());
            exc.Connection.Close();
            
return result;

        }


    }

}

 

本文转载:CSDN博客