版權(quán)聲明:轉(zhuǎn)載時請以超鏈接形式標(biāo)明文章原始出處和作者信息及本聲明
http://csolay.blogbus.com/logs/59876891.html
/*這里以一個簡單的例子說明,假設(shè)已在SQL 2005服務(wù)器上新建了數(shù)據(jù)庫Validation,并且其下有一個表login,該表有兩個字段,userName和passWord,分別指用戶名和密碼,用戶登錄界面只需驗證這兩個是否同時正確即可*/
/*注意要在對應(yīng)的頭文件中加入一句 #import "C:\Program Files\Common Files\System\ado\msado15.dll" no_namespace rename("EOF", "rsEOF")*/
m_user.TrimRight(); //修剪字符串,去掉前后無用的空格符
m_password.TrimRight();
CoInitialize(NULL); //初始化
_ConnectionPtr pConn(__uuidof(Connection)); //創(chuàng)建連接對象
_RecordsetPtr pRst(__uuidof(Recordset)); //創(chuàng)建記錄集對象
try
{
pConn->ConnectionString = (_bstr_t)loginConnStr; //CString loginConnStr = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=Validation;Data Source=083B6DCCE3934A6"; 此為連接字符串
pConn->Open("", "", "",/*adModeUnknown*/adConnectUnspecified); //連接字符串已經(jīng)設(shè)置好了,故Open前三個參數(shù)可以不寫
//pRst = pConn->Execute("select * from login", NULL, adCmdText); //通過連接執(zhí)行SQL語句返回的記錄集貌似只能用于查詢
pRst->Open("SELECT * FROM login",_variant_t((IDispatch*)pConn,true),adOpenDynamic,adLockOptimistic,adCmdText);
}
catch (_com_error e)
{
CString errormsg;
errormsg.Format(_T("Warning: 連接數(shù)據(jù)庫發(fā)生異常."));
AfxMessageBox(errormsg);
}
CString str = (char *)((_bstr_t)pRst->GetCollect("userName"));
str.TrimRight();
while (!pRst->rsEOF && m_user != str) //不是記錄集結(jié)尾且不等
{
pRst->MoveNext(); //此時可能已經(jīng)到記錄集結(jié)尾,需判斷
if (!pRst->rsEOF)
{
str = (char *)((_bstr_t)pRst->GetCollect("userName"));
str.TrimRight();
}
}
if (!pRst->rsEOF)
{
CString pwd = (char *)((_bstr_t)pRst->GetCollect("passWord"));
pwd.TrimRight();
if (m_password == pwd)
{
//登陸成功
loginUserName = m_user;
m_bIsSystemStart=TRUE;
OnOK();
}
else
{
MessageBox("密碼錯誤!");
}
}
else
{
MessageBox("此用戶不存在!");
}
ps: 注:連接字符串的產(chǎn)生的簡便方法:
data source是指數(shù)據(jù)庫所在的服務(wù)器地址。
server=localhost;uid=test;pwd=test;database=Northwind
這個就是連接字符串的寫法。
要是你比較懶的話就在桌面上建一個文本文檔。把文件后綴名改成udl
雙擊打開。
在提供程序里選一個數(shù)據(jù)庫類型
在連接里第一個寫數(shù)據(jù)庫地址。使用指定的id和pass,填完之后勾上允許保存密碼。
然后在服務(wù)器上選擇你要的數(shù)據(jù)庫。
確定
關(guān)掉
用記事本打開這個文件。會有這樣的東西
[oledb]
; Everything after this line is an OLE DB initstring
Provider=SQLOLEDB.1;Password=test;Persist Security Info=True;User ID=test;Initial Catalog=Northwind;Data Source=localhost
如果你在程序里指定了數(shù)據(jù)庫類型的話就從Password開始粘貼到最后。沒指定就從Provider開始