版权声明:转载时请以超链接形式标明文章原始出处和作者信息及本声明
http://csolay./logs/59876891.html
/*这里以一个简单的例子说明,假设已在SQL 2005服务器上新建了数据库Validation,并且其下有一个表login,该表有两个字段,userName和passWord,分别指用户名和密码,用户登录界面只需验证这两个是否同时正确即可*/
/*注意要在对应的头文件中加入一句 #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)); //创建连接对象
_RecordsetPtr pRst(__uuidof(Recordset)); //创建记录集对象
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); //连接字符串已经设置好了,故Open前三个参数可以不写
//pRst = pConn->Execute("select * from login", NULL, adCmdText); //通过连接执行SQL语句返回的记录集貌似只能用于查询
pRst->Open("SELECT * FROM login",_variant_t((IDispatch*)pConn,true),adOpenDynamic,adLockOptimistic,adCmdText);
}
catch (_com_error e)
{
CString errormsg;
errormsg.Format(_T("Warning: 连接数据库发生异常."));
AfxMessageBox(errormsg);
}
CString str = (char *)((_bstr_t)pRst->GetCollect("userName"));
str.TrimRight();
while (!pRst->rsEOF && m_user != str) //不是记录集结尾且不等
{
pRst->MoveNext(); //此时可能已经到记录集结尾,需判断
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: 注:连接字符串的产生的简便方法:
data source是指数据库所在的服务器地址。
server=localhost;uid=test;pwd=test;database=Northwind
这个就是连接字符串的写法。
要是你比较懒的话就在桌面上建一个文本文档。把文件后缀名改成udl
双击打开。
在提供程序里选一个数据库类型
在连接里第一个写数据库地址。使用指定的id和pass,填完之后勾上允许保存密码。
然后在服务器上选择你要的数据库。
确定
关掉
用记事本打开这个文件。会有这样的东西
[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
如果你在程序里指定了数据库类型的话就从Password开始粘贴到最后。没指定就从Provider开始