连接数据库的例子:如图,
新建一个基于对话框的应用程序,工程取名为:Ado,然后在该对话框资源上摆放一个列表框和一个按钮控件,并修改后者的属性,将其ID设置为IDC_BTN_QUERY ,Caption设置为“查询”。在VC中利用ADO访问数据库时,首先需要导入ADO库。本例在Ado程序的预编译头文件:stdafx.h中导入该哭,方法是利用imp
查询的命令响应函数代码如下:
void CKjlDlg::On
{
// TODO: Add your control notification handler co
CoInitialize(NULL);
_ConnectionPtr pConn(__uuidof(Connection));
_RecordsetPtr pRst(__uuidof(Recordset));
pConn->ConnectionString="Driver={MYSQL ODBC 5.1 Driver};Server=localhost;
Database=test1;User=root;Password=jiang;Option=3";
pConn->Open("","","",adConnectUnspecified);
pRst=pConn->Execute("select *from dept",NULL,adCmdText);
while(!pRst->rsEOF)
{
((CListBox*)GetDlgItem(IDC_LIST1))->AddString((_bstr_t)pRst->GetCollect("deptname"));
pRst->MoveNext();
}
pRst->Close();
pConn->Close();
pRst.Release();
pConn.Release();
CoUninitialize();
}
同样也可以用记录集智能指针对象直接执行SQL询查语句以获取记录集数据,
可以用这句 pRst->Open("select *from dept",_variant_t((IDispatch*)pConn),
adOpenDynamic,adLockOptimistic,adCmdText);代替下面的,
pRst=pConn->Execute("select *from dept",NULL,adCmdText);
在VC中同样还能利用Command智能指针对象来访问数据库。这时,上面提到的那个命令响应函数代码如下:
void CKjlDlg::On
{
// TODO: Add your control notification handler co
CoInitialize(NULL);
_ConnectionPtr pConn(__uuidof(Connection));
_RecordsetPtr pRst(__uuidof(Recordset));
_CommandPtr pCmd(__uuidof(Command));
pConn->ConnectionString="Driver={MYSQL ODBC 5.1 Driver};Server=localhost;Database=test1;User=root;Password=jiang;Option=3";
pConn->Open("","","",adConnectUnspecified);
//pRst=pConn->Execute("select *from dept",NULL,adCmdText);
//pRst->Open("select *from dept",_variant_t((IDispatch*)pConn),
//adOpenDynamic,adLockOptimistic,adCmdText);
pCmd->put_ActiveConnection(_variant_t((IDispatch*)pConn));
pCmd->CommandText="select * from dept";
pRst=pCmd->Execute(NULL,NULL,adCmdText);
while(!pRst->rsEOF)
{
((CListBox*)GetDlgItem(IDC_LIST1))->AddString((_bstr_t)pRst->GetCollect("deptname"));
pRst->MoveNext();
}
pRst->Close();
pConn->Close();
pCmd->Release();
pRst.Release();
pConn.Release();
CoUninitialize();
}
注意:pRst=pCmd->Execute(NULL,NULL,adCmdText);只读的记录,要是要返回可以读写的操作则应该用:
pRst->Open("select *from login",_variant_t((IDispatch *)pConn,true),