MFC利用ADO建立access数据源 ---包括访问带access密码与不带access密码两种方式)

void CDlg_login::OnButton1()
{

CString c_user,c_password;
m_user1.GetWindowText(c_user);
m_password1.GetWindowText(c_password);


if (c_user.IsEmpty()||c_user.IsEmpty())
{
 MessageBox("用户名密码不能为空!","提示",64);
}

m_pConnection.CreateInstance(__uuidof(Connection));
m_pRecordset.CreateInstance(__uuidof(Recordset));
CString strJet ="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=.\\DataBase.mdb";
m_pConnection->Open(strJet.AllocSysString(),"","",adModeUnknown);

CString sql;
 sql.Format("select *from employees where name='%s' and password='%s'",c_user,c_password);
m_pRecordset->Open(sql.AllocSysString(), m_pConnection.GetInterfacePtr(),adOpenDynamic,adLockOptimistic,-1);

if (c_user==(user = m_pRecordset->GetCollect("name").bstrVal) &&c_password== (password = m_pRecordset->GetCollect("password").bstrVal))
{
 CDialog::OnOK();
 CLOGINDlg dlg;
 dlg.DoModal();

}

 

 

 

实例二,连接数据据至登录对话框(其中部分代码注释加//,仅用来调试期间用,可供参考),代码实现如下:

try
 {
  this->UpdateData(true);

  //  if (this->m_username.IsEmpty()||this->m_password.IsEmpty())
  //  {
  //   MessageBox("用户名,密码不能为空!","登录提示",MB_ICONQUESTION);
  //  }

  ::CoInitialize(NULL);

  this->m_pConnection.CreateInstance(__uuidof(Connection));

  this->m_pRecordset.CreateInstance(__uuidof(Recordset));


  // this->m_pConnection->Open("DSN=staff_dns","","",0);//上面四行为打开数据源连接,此方法使用本地DSN数据源


  // CString strJet ="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=staff.mdb";  //访问不带密码的access数据库


  CString strJet ="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=staff.mdb;Jet OLEDB:Database Password=sdoa0806";   //访问带密码的access数据库方法

  this->m_pConnection->Open(strJet.AllocSysString(),"","",adModeUnknown);

  CString str;

  str.Format("select * from tb_staff where username='%s' and password='%s'",this->m_username,this->m_password);

  BSTR bstrSQL=str.AllocSysString();

  this->m_pRecordset->Open(bstrSQL,(IDispatch*)this->m_pConnection,adOpenDynamic,adLockOptimistic,adCmdText);

  if(!this->m_pRecordset->adoEOF)

  {


   //   CDebugDlg dlg1;
   //   UpdateData(false);
   //   GetDlgItemText(IDC_EDIT1,dlg1.m_user);
   //   MessageBox(dlg1.m_user);
   //   dlg1.m_StatusBar.SetPaneText(3,m_username);

   CDialog::OnOK();
   //MessageBox("调用成功!");
   OutputDebugString("登录成功!");

   UpdateData(TRUE);

   GetDlgItemText(IDC_EDIT_USERNAME,m_username);

   //MessageBox(m_username,"1");

   dlg_confirm.m_user=m_username;
   // MessageBox(dlg_confirm.m_user,"2");

   UpdateData(FALSE);

   dlg_confirm.DoModal();


  }

  else

   MessageBox("用户名,密码输入错误,登录失败!","登录提示",MB_ICONQUESTION);

 

 }
 catch (...)     //增加try...catch异常抛出
 {
  
   AfxMessageBox("数据库连接失败,确认数据库名称与路径是否正确!");  
   return ;
 } 

 

 this->m_pRecordset->Close();

 this->m_pConnection->Close();

 ::CoUninitialize();

}

posted @ 2013-09-06 00:25  狂师  阅读(439)  评论(0编辑  收藏  举报