当前位置:编程问答 > C#/ASP.NET >

C#中连接access的连接类

问题:要用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;
}
}

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

string strConnection = "Provider=Microsoft.Jet.OleDb.4.0;Data Source=C:\\db\\sys.mdb";
var con = new OleDbConnection(strConnection);

var dap = new OleDbDataAdapter("select * from 用户表", con);
var ds = new DataSet();
dap.Fill(ds, "用户表");
//bindingSource1.Add(ds.Tables[0].DefaultView);
this.dataGridView1.DataSource = ds.Tables[0].DefaultView;
con.Dispose();

上一个:关于c#的一些相关问题?
下一个:Java 和 C#的 区别是什么

CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,