{
// TODO: Add your control notification handler code here
try
{
//创建实例
m_Recordset.CreateInstance(__uuidof(Recordset));
//将控件中的值保存到变量中,主要是保存SQL 语句
UpdateData(TRUE);
//设定光标服务
m_Connection->CursorLocation = adUseClient;
//根据连接字符串开启数据连接,得到结果集
m_Recordset->Open(m_strSQL.GetBuffer(0), m_Connection.GetInterfacePtr(), adOpenDynamic,
adLockOptimistic, adCmdText);
}
//捕获例外_com_error
catch (_com_error &e)
{
GenerateError(e.Error(), e.Description());
}
//捕获其他例外
catch (...) {}
//将结果集中的内容在datagrid 中显示出来
m_DataGrid.SetRefDataSource((LPUNKNOWN)m_Recordset);
//刷新DataGrid
m_DataGrid.Refresh();
//将变量中的值保存到控件中
UpdateData(FALSE);
//将结果集置空
m_Recordset = NULL;
}
在这段代码中,完成了执行SQL 语句。这是因为记录集转化成LPUNKNOWN 类型,然
后当做参数传给DataGrid 控件的方法SetRefDataSource 即可。
至此,程序已经可以完成对数据库的cāo作了,但是为了让程序更加完善,当cāo作结束时,
应该关闭记录集和连接,然后退出。最后还需要为“断开”和“退出”按钮编写响应函数。
“断开”按钮的响应函数如下:
void CAdoTestView::OnDisconnect()
{
枫叶文学网www.fywxw.com
Visual C++ 6.0 程序设计从入门到精通
·364·
// TODO: Add your control notification handler code here
try
{
//关闭连接
m_Connection->Close();
}
//捕获_com_error 例外
catch (_com_error &e)
{
GenerateError(e.Error(), e.Description());
}
//捕获其他例外
catch(...) {}