`
smartgz
  • 浏览: 68240 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
最近访客 更多访客>>
社区版块
存档分类
最新评论

C#连接ACCESS数据库的类

阅读更多
      首先在web.config里面的<configuration>与</configuration>之间添加如下:

<appSettings>
  <add key="connString" value="Data Source=E:\Develop\editor\App_Data\db.mdb" />
  </appSettings>

    推荐做法是把数据库文件放在App_Data目录下,即使人家知道路径也是禁止下载的。
    对应的App_code目录下的类

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.OleDb;//这个是添加的引用
///
/// 这个是操作Access数据库的类,提供2个方法,getSQLTable获取表,executeSQL执行所需要的SQL语句
///
public class dbClient
{  
    private string connectionString;   
 public dbClient()//构造连接字符串
 {
        connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;";       
        connectionString +=@System.Configuration.ConfigurationSettings.AppSettings["connString"].ToString();
        //加了@是为了不让\字符变为转义字符
        //充分利用系统自带的方法来访问web.config配置文件
 }
    public OleDbConnection createConnection()//返回一个连接
    {
        return new OleDbConnection(connectionString);
    }
    public DataTable getSQLTable(string selectSQL, string tableName)//获得一个表,2个参数,一个SQL语句,一个表名
    {
        DataTable table = new DataTable(tableName);
        OleDbConnection oleConnection = this.createConnection();
        try
        {           
            OleDbDataAdapter oleDataAdapter = new OleDbDataAdapter(selectSQL, connectionString);
            oleDataAdapter.Fill(table);           
        }
        catch (System.Data.OleDb.OleDbException ex)
        {
            throw ex;
        }
        catch (System.Exception ex)
        {
            throw ex;
        }
        finally
        {
            if (oleConnection.State != ConnectionState.Closed)
            {
                oleConnection.Close();
            }
        }
        return table;
    }
    public int executeSQL(string cmdText)//执行SQL语句,1个参数,为所执行的语句,返回整数值为判断所影响的行数
    {
        int iValue = -1;
        OleDbConnection oleConnecion = this.createConnection();
        oleConnecion.Open();
        OleDbTransaction oleTransaction = oleConnecion.BeginTransaction();
        try
        {
            OleDbCommand oleCommand = new OleDbCommand();
            oleCommand.Connection = oleConnecion;         
            oleCommand.CommandText = cmdText;
            oleCommand.Transaction = oleTransaction;
            iValue = oleCommand.ExecuteNonQuery();
            oleTransaction.Commit();
        }
        catch (System.Data.OleDb.OleDbException ex)
        {
            oleTransaction.Rollback();
            throw ex;
        }
        catch (System.Exception ex2)
        {
            throw ex2;
        }
        finally
        {
            oleConnecion.Close();
        }
        return iValue;
    }   
   }


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics