首先在头文件中包含#import"C:/Program Files/Common Files/System/ado/msado15.dll" rename("EOF","ADOEOF") 并创建连接对象ADODB::_ConnectionPtr m_connection;
在CPP中:
初始化 LISTCTRL:
m_listCtrl.InsertColumn(0,_T("工程名"),LVCFMT_CENTER,100);
m_listCtrl.InsertColumn(1,_T("左边界"),LVCFMT_CENTER,100);
m_listCtrl.InsertColumn(2,_T("上边界"),LVCFMT_CENTER,100);
m_listCtrl.InsertColumn(3,_T("右边界"),LVCFMT_CENTER,100);
m_listCtrl.InsertColumn(4,_T("下边界"),LVCFMT_CENTER,100);
m_listCtrl.SetExtendedStyle(LVS_EX_FULLROWSELECT|LVS_EX_GRIDLINES);// 设置整行选择
//连接数据库函数
int CDBConnectDlg::open(LPCTSTR server,LPCTSTR db, LPCTSTR user ,LPCTSTR password)
{
HRESULT comhr=::CoInitialize(NULL);
if (FAILED(comhr))
{
return -1;
}
HRESULT hr = m_connection.CreateInstance(__uuidof(ADODB::Connection));
if (FAILED(hr))
return -1;
CString str;
str.Format(_T("Driver=SQL Server;Server=%s;DATABASE=%s"),server, db);
try
{
// 连接到服务器上数据库
m_connection->Open((LPCTSTR)str, user, password,ADODB::adModeUnknown) ;
if (FAILED(hr))
return -1;
}
catch (_com_error &err)
{
TRACE(_T("数据库操作失败! 错误信息:%s, 文件:%s, 行:%d./n"), err.ErrorMessage(), __FILE__, __LINE__);
return -1;
}
return 0;
}
void CDBConnectDlg::OnBnClickedOk()
{
// TODO: 在此添加控件通知处理程序代码
UpdateData(true);
if (this->open(m_strDbsever,m_strDbname,m_strUserName,m_strUserPwd)==-1)
{
AfxMessageBox(_T("数据库出问题了,老大!"),MB_OK,NULL);
return;
}
// 创建Command对象
ADODB::_CommandPtr cmd;
HRESULT hr = cmd.CreateInstance(__uuidof(ADODB::Command));
if (FAILED(hr)) return;
CString str = _T("SELECT * From TABLE_PROJECT");
cmd->ActiveConnection = m_connection;
cmd->CommandText = (LPCTSTR)str;
cmd->CommandType = ADODB::adCmdText;
try
{
// 查询所有工程信息
ADODB::_RecordsetPtr rs = cmd->Execute(NULL, NULL, ADODB::adCmdUnknown);
if (FAILED(hr)) return ;
int i = 0;
rs->MoveFirst();
while (!rs->GetADOEOF())
{
// 获取工程的所有属性
_variant_t prj_id = rs->GetCollect("PROJECT_ID"); // 名称
_variant_t left = rs->GetCollect("COVERAGE_LEFT"); // 左边界
_variant_t top = rs->GetCollect("COVERAGE_TOP"); // 上边界
_variant_t right = rs->GetCollect("COVERAGE_RIGHT"); // 右边界
_variant_t bottom = rs->GetCollect("COVERAGE_BOTTOM"); // 下边界
_variant_t width = rs->GetCollect("CELL_WIDTH"); // 分幅宽度
_variant_t height = rs->GetCollect("CELL_HEIGHT"); // 分幅高度
m_listCtrl.InsertItem(i, CString(LPSTR (_bstr_t(prj_id))));
m_listCtrl.SetItemText(i, 0, CString(LPSTR (_bstr_t(prj_id))));
m_listCtrl.SetItemText(i, 1, CString(LPSTR (_bstr_t(left))));
m_listCtrl.SetItemText(i, 2, CString(LPSTR (_bstr_t(top))));
m_listCtrl.SetItemText(i, 3, CString(LPSTR (_bstr_t(right))));
m_listCtrl.SetItemText(i, 4, CString(LPSTR (_bstr_t(bottom))));
rs->MoveNext();
++i;
}
}
catch (_com_error &err)
{
TRACE(_T("数据库操作失败! 错误信息:%s, 文件:%s, 行:%d./n"), err.ErrorMessage(), __FILE__, __LINE__);
return ;
}
return ;
OnOK();
}