access数据的连接及语句执行操作,不难,久不用会生疏,每次都要找资料,干脆自己整理下,记录下来,需要的时候,直接查看,提高效率。也供初学者参考
1、连接字符串
public static string strconn = @"provider=microsoft.jet.oledb.4.0;data source=" directory.getcurrentdirectory() "\\**.mdb;";
2、数据语句执行(差改,用户名查重,根据用户获取密码)
//获取所有数据集--返回所有数据
public static dataset executequery(string strsql) //strsql需要执行的查询语句
{
using (oledbconnection conn = new oledbconnection(strconn))
{
try
{
if (conn.state != connectionstate.open)
{
conn.open();
}
oledbdataadapter adapter = new oledbdataadapter(strsql, strconn);
dataset ds = new dataset();
adapter.fill(ds);
return ds;
}
catch (oledbexception ole)
{
throw ole;
}
finally
{
conn.close();
}
}
}
//增删改的查询语句的执行--返回受影响行数
public static int executenonquery(string strsql) //strsql需要执行的查询语句
{
try
{
using (oledbconnection conn = new oledbconnection(strconn))
{
if (conn.state != connectionstate.open)
{
conn.open();
}
oledbcommand cmd = new oledbcommand(strsql, conn);
//执行事务,事务将控制和维护事务中每个操作的一致性和完整性
oledbtransaction ts = conn.begintransaction();
cmd.transaction = ts;
int iret = cmd.executenonquery();
if (iret > 0)
{
ts.commit();//如果返回数据大于0,执行操作
}
else
{
ts.rollback();//不为0,则回滚
}
return iret;
}
}
catch (oledbexception oledbexception)
{
throw oledbexception;
}
}
/// 查询返回第一行数据---根据用户名查密码(返回根据用户名返回的一条数据)
public static datarow executerow(string strloginsql) //strsql需要执行的查询语句
{
datarow row;
using (oledbconnection conn = new oledbconnection(strconn)) //尝试链接数据库
{
try
{
if (conn.state != connectionstate.open)
{
conn.open();
}
oledbdataadapter adapter = new oledbdataadapter(strloginsql, strconn);//实例化一个数据适配器
datatable ds = new datatable();
adapter.fill(ds);//将数据填充到适配器中
if (ds.rows.count == 0)
{
row = null;
}
else
{
row = ds.rows[0];
}
}
catch (exception ex)
{
return null;
}
finally
{
conn.close();
}
}
return row;
}
/// 查询结果,返回第一行第一列----用于查重(注册用户名是否已经存在,插入数据是否已经存在)---返回0、1
public static int executescalar(string strsql) //strsql需要执行的查询语句
{
try
{
using (oledbconnection conn = new oledbconnection(strconn))
{
if (conn.state != connectionstate.open)
{
conn.open();
}
oledbcommand cmd = new oledbcommand(strsql, conn);
object obj = cmd.executescalar();
if (obj != null && !convert.isdbnull(obj))
{
return 1;
}
else
{
return 0;
}
}
}
catch (oledbexception oledbexception)
{
throw oledbexception;
}
}
主要对这个方法留个备份,也供初学使用者参考。