实现用access简单的登录功能:
首先建立个access数据库login.mdb:
新建一个表UserInfo,包括两个字段UserName和PassWord.都是文本类型。
界面字面变量定义:
导入类库:
在StdAfx.h添加代码
#import "C:\Program Files\Common Files\System\ado\msado15.dll" no_namespace rename("EOF","adoEOF")
在app类中声明连接对象
class CAdoAccessTest1App : public CWinApp
{
public:
//声明连接对象
_ConnectionPtr m_pConnection;
CAdoAccessTest1App();
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CAdoAccessTest1App)
public:
virtual BOOL InitInstance();
virtual int ExitInstance();
//}}AFX_VIRTUAL
// Implementation
//{{AFX_MSG(CAdoAccessTest1App)
// NOTE - the ClassWizard will add and remove member functions here.
// DO NOT EDIT what you see in these blocks of generated code !
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
在app中的InitInstance()中添加初始化代码:
AfxEnableControlContainer();
// Standard initialization
// If you are not using these features and wish to reduce the size
// of your final executable, you should remove from the following
// the specific initialization routines you do not need.
//初始化com库
CoInitialize(NULL);
try
{
HRESULT hr;
//创建Connection实例对象
hr = m_pConnection.CreateInstance("ADODB.Connection");
if(SUCCEEDED(hr))
{
m_pConnection->ConnectionTimeout = 8;//设置超时时间为8秒
m_pConnection->PutCursorLocation(adUseClient);//这是设置游标的,游标在服务器端还是客户端决定了你能够采用的打开模式 ,不同的数据库支持不同。
hr = m_pConnection->Open("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=.\\login.mdb;Persist Security Info=False","","",adModeUnknown);
}
}
catch (_com_error e)
{//异常处理
CString temp;
temp.Format("连接数据库错误信息:%s",e.ErrorMessage());
::MessageBox(NULL,temp,"提示信息",NULL);
return FALSE;
}
#ifdef _AFXDLL
引用theApp变量,注意添加extern关键字:
extern CAdoAccessTest1App theApp;
相应登录按钮的函数:
void CAdoAccessTest1Dlg::OnOK()
{
// TODO: Add extra validation here
//更新数据
UpdateData(TRUE);
//初始化记录集
_RecordsetPtr pRs("ADODB.Recordset");
//构建SQL语句
CString strSQL;
strSQL.Format("select * from UserInfo where UserName = '%s' and PassWord = '%s'",m_sUserName,m_sPassword );
//打开指点记录集
pRs->Open(_variant_t(strSQL.GetBuffer(strSQL.GetLength())),
_variant_t(theApp.m_pConnection,true),
adOpenStatic,
adLockOptimistic,
adCmdText
);
//访问记录集中的数据
if(pRs->GetRecordCount() > 0)
{
MessageBox("登录成功!!");
}
else
{
MessageBox("登录失败!!");
}
//关闭记录集
pRs->Close();
// CDialog::OnOK();
}
在app类中的ExitInstance()函数释放资源:
int CAdoAccessTest1App::ExitInstance()
{
// TODO: Add your specialized code here and/or call the base class
if(m_pConnection->State)
{
//释放资源
m_pConnection->Close();
m_pConnection.Release();
}
return CWinApp::ExitInstance();
}