㈠ wex5怎么连接数据库
//初始化数据库连接
::CoInitialize(NULL);
连接数据库
[cpp] view plainprint?
BOOL CLogin::ConnectDB(void)
{
HRESULT hr = NULL;
try
{
hr = m_pConnection.CreateInstance("ADODB.Connection");///创建 Connection 对象
if(SUCCEEDED(hr))
{
//登录数据库并连接数据库DBCourse
//这里的server不能写成127.0.0.1否则会出现未指定的错误,应该写成Sql server登录界面的服务器名称
m_pConnection->ConnectionString = "driver={SQL Server};server=LOGO-PC\\LOGO;uid=DBCourse;pwd=DBCourse;";
m_pConnection->Open("","","",adConnectUnspecified);
m_pConnection->DefaultDatabase = "DBCourse";
}
else
{
AfxMessageBox(TEXT("创建 Connection 对象失败"));///显示错误信息
return FALSE;
}
}
catch(_com_error e)///捕捉异常
{
CString errormessage;
errormessage.Format( TEXT("连接数据库失败 !\r\n 错误信息 :%s(%ld)"),e.ErrorMessage(),e.Error() );
AfxMessageBox(errormessage);///显示错误信息
return FALSE;
}
return TRUE;
}
操作数据库
[cpp] view plainprint?
void CLogin::OnBnClickedButton1()
{
if( m_user.GetWindowTextLength()<=0 || m_password.GetWindowTextLength()<=0 )
{
MessageBox(TEXT("请输入用户名或密码!"), TEXT("错误:用户名或密码为空"), MB_OK | MB_ICONWARNING );
return;
}
if( FALSE==this->ConnectDB() ) return;
TCHAR szUserName[20];
TCHAR szPassword[50];
TCHAR szSql[MAX_PATH];
//获取用户输入的用户名和密码
m_user.GetWindowText( szUserName, 20 );
m_password.GetWindowText( szPassword, 50 );
//创建_RecordsetPtr用来执行数据库操作
_RecordsetPtr pRecordset;
pRecordset.CreateInstance("ADODB.Recordset");
_tcscpy_s( szSql, TEXT("select * from usr where uname='") );
_tcscat_s( szSql, szUserName );
_tcscat_s( szSql, TEXT("' and passwd='") );
_tcscat_s( szSql, szPassword );
_tcscat_s( szSql, TEXT("';") );
pRecordset->Open(_variant_t(szSql), _variant_t ((IDispatch*) m_pConnection,true), adOpenStatic, adLockOptimistic, adCmdText);
int nResult = DLG_RESULT_OK;
if( pRecordset->RecordCount>0 )
{
//MessageBox(TEXT("登录成功!"), szUserName, MB_OK | MB_ICONINFORMATION );
}
else
{
MessageBox(TEXT("用户名或密码错误!"), TEXT("登录失败!"), MB_OK | MB_ICONINFORMATION );
nResult = DLG_RESULT_ERROR;
}
pRecordset->Close();
if( DLG_RESULT_OK==nResult ) Exit( DLG_RESULT_OK );
}
哦忘了一件事了,还需要在stafx.h文件中引入dll文件的,如此
[cpp] view plainprint?
//添加dll库
#import "c:\program files\common files\system\ado\msado15.dll" no_namespace rename("EOF","adoEOF")
//添加dll库
//添加宏定义
#define DLG_RESULT_OK 1
#define DLG_RESULT_ERROR 2
#define DLG_RESULT_CANCEL 3
//添加宏定义