今天做个小项目,需要asp.net连接access,对其操作,本人经常使用sql server,但是操作access还是比较陌生,
只是以前上学的时候应用过,都忘完了,今天使用,然后上网搜了下资料,整理了一下,以备以后使用。

1、asp.net连接access数据库,方法有3中,看一下代码:


using System.Data.OleDb;
1)OleDbConnection conn = new OleDbConnection(ConfigurationManager.AppSettings["AccessConn"]);
2)public static string connectionString = “Provider=Microsoft.Jet.OLEDB.4.0; Data Source=|DataDirectory|test.mdb”;
3)OleDbConnection conn = new OleDbConnection(“Provider=Microsoft.Jet.OLEDB.4.0; Data Source=|DataDirectory|test.mdb”)

2、基本操作:增删查改

aspx.cs

//获得数据集

GridView1.DataSource = mypub.GetDataSet(“select * from Messages”, “Messages”);
GridView1.DataBind();

//获得数据行数

string TabNum= mypub.GetResult(“select count(*) from Messages”);

//删除数据

int num = mypub.ExecSql(“delete from Messages where Name=’weixing’”);

//插入数据

mypub.ExecSql(“insert into Messages (Name,Email,Url,CTime) values (‘weixing’,'weixing@qq.com’,’http://www.ivvdd.com‘,’” + creatime + “‘) “).ToString();

pub.cs

public System.Data.DataSet GetDataSet(string sQueryString, string TableName) //返回结果集
{
OleDbConnection conn = new OleDbConnection(ConfigurationManager.AppSettings["AccessConn"]);
conn.Open();
OleDbDataAdapter dbAdapter = new OleDbDataAdapter(sQueryString,conn);
DataSet dataset = new DataSet();
dbAdapter.Fill(dataset, TableName);
conn.Close();
conn.Dispose();
return dataset;
}

public int ExecSql(string strsql) //返回值为影响的行数
{
OleDbConnection conn = new OleDbConnection(ConfigurationManager.AppSettings["AccessConn"]);
conn.Open();
OleDbCommand cmd = new OleDbCommand(strsql, conn);
int cmd_num = 0;
//执行成功
try
{
cmd_num=cmd.ExecuteNonQuery();
conn.Close();
conn.Dispose();
}
//执行失败
catch
{
conn.Close();
conn.Dispose();
return 0;
}
return cmd_num;
}

public string GetResult(string strsql)
{
OleDbConnection conn = new OleDbConnection(ConfigurationManager.AppSettings["AccessConn"]);
conn.Open();
OleDbCommand cmd = new OleDbCommand(strsql,conn);
string myresult = Convert.ToString(cmd.ExecuteScalar());
conn.Close();
conn.Dispose();
return myresult;
}