4,011
社区成员
发帖
与我相关
我的任务
分享
void CfaceDlg::OnBnClickedButton1()
{
// TODO: 在此添加控件通知处理程序代码
_ConnectionPtr pMyConnect = NULL;
HRESULT hr = pMyConnect.CreateInstance(__uuidof(Connection));
if (FAILED(hr))
return;
//初始化链接参数
_bstr_t strConnect = "Provider=SQLOLEDB;Server=li-PC;Database=face;uid=root; pwd=123456;"; //Database指你系统中的数据库
//执行连接
try
{
// Open方法连接字串必须四BSTR或者_bstr_t类型
pMyConnect->Open(strConnect, "", "", NULL);
}
catch(_com_error &e)
{
MessageBox(e.Description(), _T("警告"), MB_OK|MB_ICONINFORMATION);
}//发生链接错误
//定义_RecordsetPtr变量,调用它Recordset对象的Open,即可打开一个数据集
//初始化过程 以下是个实例
_RecordsetPtr pRecordset;
if (FAILED(pRecordset.CreateInstance(__uuidof(Recordset))))
{
return;
}
//执行操作
try
{
pRecordset->Open(_variant_t("t_face"),
_variant_t((IDispatch*)pMyConnect),
adOpenKeyset, adLockOptimistic, adCmdTable);
}
catch (_com_error &e)
{
MessageBox(e.Description(), _T("无法打开t_face表"), MB_OK|MB_ICONINFORMATION);
}
pMyConnect.CreateInstance(__uuidof(Connection));
//初始化Connection指针
pRecordset.CreateInstance(__uuidof(Recordset));
//初始化Recordset指针
CString strSql("select * from t_face");//具体执行的SQL语句
pRecordset=pMyConnect->Execute(_bstr_t(strSql),NULL,adCmdText);//将查询数据导入m_pRecordset数据容器
while(!pRecordset->adoEOF)//遍历并读取name列的记录并输出
{
CString temp = (TCHAR *)(_bstr_t)pRecordset->GetFields()->GetItem ("name")->Value;
AfxMessageBox(temp);
pRecordset->MoveNext();
}
}
if (pMyConnect== NULL)
return;
_variant_t vRecsAffected ;
try
{
pRecordset= pMyConnect->Execute(strSql,
&vRecsAffected,
adOptionUnspecified) ;
}
catch(_com_error e)
{
pRecordset= NULL;
}
while(!(pRecordset->adoEOF || pRecordset->BOF))
{
_variant_t var = pRecordset->GetCollect(_T("name"));
if (var.vt == VT_BSTR) //要是字符串类型才可以 如果是其他类型 请填写其他类型
{
CString temp(var.bstrVal);
AfxMessageBox(temp);
}
pRecordset->MoveNext();
}