版權聲明:轉載時(shí)請以超鏈接形式標明文章原始出處和作者信息及本聲明
http://csolay.blogbus.com/logs/59876891.html
/*這里以一個(gè)簡(jiǎn)單的例子說(shuō)明,假設已在SQL 2005服務(wù)器上新建了數據庫Validation,并且其下有一個(gè)表login,該表有兩個(gè)字段,userName和passWord,分別指用戶(hù)名和密碼,用戶(hù)登錄界面只需驗證這兩個(gè)是否同時(shí)正確即可*/
/*注意要在對應的頭文件中加入一句 #import "C:\Program Files\Common Files\System\ado\msado15.dll" no_namespace rename("EOF", "rsEOF")*/
m_user.TrimRight(); //修剪字符串,去掉前后無(wú)用的空格符
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)設置好了,故Open前三個(gè)參數可以不寫(xiě)
//pRst = pConn->Execute("select * from login", NULL, adCmdText); //通過(guò)連接執行SQL語(yǔ)句返回的記錄集貌似只能用于查詢(xún)
pRst->Open("SELECT * FROM login",_variant_t((IDispatch*)pConn,true),adOpenDynamic,adLockOptimistic,adCmdText);
}
catch (_com_error e)
{
CString errormsg;
errormsg.Format(_T("Warning: 連接數據庫發(fā)生異常."));
AfxMessageBox(errormsg);
}
CString str = (char *)((_bstr_t)pRst->GetCollect("userName"));
str.TrimRight();
while (!pRst->rsEOF && m_user != str) //不是記錄集結尾且不等
{
pRst->MoveNext(); //此時(shí)可能已經(jīng)到記錄集結尾,需判斷
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("此用戶(hù)不存在!");
}
ps: 注:連接字符串的產(chǎn)生的簡(jiǎn)便方法:
data source是指數據庫所在的服務(wù)器地址。
server=localhost;uid=test;pwd=test;database=Northwind
這個(gè)就是連接字符串的寫(xiě)法。
要是你比較懶的話(huà)就在桌面上建一個(gè)文本文檔。把文件后綴名改成udl
雙擊打開(kāi)。
在提供程序里選一個(gè)數據庫類(lèi)型
在連接里第一個(gè)寫(xiě)數據庫地址。使用指定的id和pass,填完之后勾上允許保存密碼。
然后在服務(wù)器上選擇你要的數據庫。
確定
關(guān)掉
用記事本打開(kāi)這個(gè)文件。會(huì )有這樣的東西
[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
如果你在程序里指定了數據庫類(lèi)型的話(huà)就從Password開(kāi)始粘貼到最后。沒(méi)指定就從Provider開(kāi)始
聯(lián)系客服