在stdafx.cpp文件中加入
#import "c:\program files\common files\system\ado\msado15.dll" no_namespace rename("EOF", "adoEOF")
在CxxApp中与数据库建立链接
_ConnectionPtr m_pConnection;//连接对象
AfxOleInit(); //初始化com库,如果不加,编译可以通过,但运行时会报错
m_pConnection.CreateInstance(__uuidof(Connection)); //创建连接对象
//这个数据库的链接比较简单
try
{
m_pConnection->Open("DSN=dictionary",//连接dictionary数据源
_bstr_t(""),
_bstr_t(""),
adConnectUnspecified);
}
catch (_com_error e)
{
AfxMessageBox("数据库连接失败,检查是否正确配置ODBC数据源!");
return FALSE;
}
在CxxView中操作数据库
CxxView继承于ListView
在文档视图中建立列表控件
//写入到初始化函数中
CListCtrl &listCtl = GetListCtrl(); //得到控件
LONG lStyle = GetWindowLong(listCtl.m_hWnd, GWL_STYLE); //获取风格
lStyle |= LVS_REPORT; //汇报风格
SetWindowLong(listCtl.m_hWnd, GWL_STYLE, lStyle); //设置style
DWORD dwStyle = ListView_GetExtendedListViewStyle(listCtl); //得到扩展风格
dwStyle|= LVS_EX_FULLROWSELECT | LVS_EX_GRIDLINES; //增加选择整行网格线风格
ListView_SetExtendedListViewStyle (listCtl, dwStyle);
int nCol; //列
LV_COLUMN lvCol; //结构
lvCol.mask = LVCF_FMT |LVCF_WIDTH | LVCF_TEXT | LVCF_SUBITEM;
CRect clientRect;
listCtl.GetClientRect(&clientRect);
//第一列
nCol = 0;
lvCol.iSubItem = nCol;
lvCol.pszText = "Word";
lvCol.fmt = LVCFMT_LEFT;
lvCol.cx = (float)clientRect.Width()/100 * 30;
listCtl.InsertColumn(nCol, &lvCol);
//第二列
nCol = 1;
lvCol.iSubItem = nCol;
lvCol.pszText = "Meaning1";
lvCol.fmt = LVCFMT_LEFT;
lvCol.cx = (float)clientRect.Width()/100 * 40;
listCtl.InsertColumn(nCol, &lvCol);
//第三列
nCol = 2;
lvCol.iSubItem = nCol;
lvCol.pszText = "Meaning2";
lvCol.fmt = LVCFMT_LEFT;
lvCol.cx = (float)clientRect.Width()/100 * 30;
listCtl.InsertColumn(nCol, &lvCol);
//在CxxView中写入更新
_RecordsetPtr m_pRecordSet; //记录集对象
m_pRecordSet.CreateInstance(__uuidof(Recordset));//创建记录集指针
CListCtrl &listCtl = GetListCtrl(); //得到列表视图控件
listCtl.DeleteAllItems(); //删除所有数据项
try
{
int nIndex=0; //记录序号
CString strSQL = "select * from EToC"; //读取所有记录
m_pRecordSet->Open(_variant_t(strSQL),
theApp.m_pConnection.GetInterfacePtr(),
adOpenDynamic,
adLockOptimistic,
adCmdText);
while (!m_pRecordSet->adoEOF)//记录尾
{
_variant_t var; //临时变量
CString strWord; //单词
CString strMeaning1; //单词含义1
CString strMeaning2; //单词含义2
//读取“word”字段
var = m_pRecordSet->GetCollect("word");
if (var.vt != VT_NULL)
{
strWord = (LPCSTR)_bstr_t(var);
}else
{
strWord = "";
}
//读取“meaning1”字段
var = m_pRecordSet->GetCollect("meaning1");
if (var.vt != VT_NULL)
{
strMeaning1 = (LPCSTR)_bstr_t(var);
}else
{
strMeaning1 = "";
}
//读取“meaning2”字段
var = m_pRecordSet->GetCollect("meaning2");
if (var.vt != VT_NULL)
{
strMeaning2 = (LPCSTR)_bstr_t(var);
}else
{
strMeaning2 = "";
}
//插入数据项
listCtl.InsertItem(nIndex, strWord); //名称
listCtl.SetItemText(nIndex,1,strMeaning1); //含义1
listCtl.SetItemText(nIndex,2,strMeaning2); //含义2
m_pRecordSet->MoveNext(); //移动记录
nIndex++; //记录序号加1
}
m_pRecordSet->Close();//关闭
}
catch(_com_error *e)
{
AfxMessageBox(e->ErrorMessage());
}
catch(...)
{
AfxMessageBox("访问数据库服务器时发生异常。");
return;
}