// TODO: 在此添加额外的初始化代码
//初始化ADO环境
if (!AfxOleInit()) { AfxMessageBox(L"OLE初始化失败"); return FALSE; }
//设置ListView例标题
m_list.SetExtendedStyle(LVS_EX_GRIDLINES | LVS_EX_FULLROWSELECT);
m_list.InsertColumn(0, L"ID", LVCFMT_CENTER, 80);
m_list.InsertColumn(1, L"mName", LVCFMT_CENTER, 80);
m_list.InsertColumn(2, L"mSex", LVCFMT_CENTER, 80);
m_list.InsertColumn(3, L"mAge", LVCFMT_CENTER, 80);
m_list.InsertColumn(4, L"mTel", LVCFMT_CENTER, 120);
//连接数据库
m_pConnection.CreateInstance(__uuidof(Connection));
try
{
//下面这些字符串弄了好久才弄对,主要是文件路径的问题吧,现在也没弄明白,放在工程Debug目录下就连接不上.
//_bstr_t connStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=myDate1.accdb;Persist Security Info=False"; //这句就出错,查了好久哦,都想放弃了.
_bstr_t connStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\\AccessData2007\\myDate1.accdb;Persist Security Info=False";
_bstr_t dataName = "Admin";
_bstr_t dataPass = "";
HRESULT hr=m_pConnection->Open(connStr,dataName,dataPass,adModeUnknown);
//MessageBox(L"数据连接成功");
}
catch (_com_error e)
{
AfxMessageBox( e.ErrorMessage());
return FALSE;
}
//连接记录集
m_pRecordset.CreateInstance(__uuidof(Recordset));
try
{
_variant_t sql = "select * from myTable";
HRESULT hret = m_pRecordset->Open(
sql,
m_pConnection.GetInterfacePtr(),
adOpenDynamic,
adLockOptimistic,
adCmdText
);
//MessageBox(L"连接成功");
}
catch (_com_error* e)
{
MessageBox(e->ErrorMessage());
return FALSE;
}
//加载数据到ListView控件中
_variant_t var;
CString strTmp;
for (int i=0;!m_pRecordset->adoEOF;i++)
{
var = m_pRecordset->GetCollect(_T("ID"));
strTmp = (LPCTSTR)_bstr_t(var);
m_list.InsertItem(i, strTmp);
var = m_pRecordset->GetCollect(_T("mName"));
strTmp = (LPCTSTR)_bstr_t(var);
m_list.SetItemText(i, 1, strTmp);
var = m_pRecordset->GetCollect(_T("mSex"));
strTmp = (LPCTSTR)_bstr_t(var);
m_list.SetItemText(i, 2, strTmp);
var = m_pRecordset->GetCollect(_T("mAge"));
strTmp = (LPCTSTR)_bstr_t(var);
m_list.SetItemText(i, 3, strTmp);
var = m_pRecordset->GetCollect(_T("mTel"));
strTmp = (LPCTSTR)_bstr_t(var);
m_list.SetItemText(i, 4, strTmp);
m_pRecordset->MoveNext();
}
//关闭记录集和数据库连接
m_pRecordset->Close();
m_pRecordset.Release();
m_pRecordset = NULL;
if (m_pConnection->State)
{
m_pConnection->Close();
}
m_pConnection = NULL;
//关闭记录集和数据库连接 m_pRecordset->Close(); m_pRecordset.Release(); m_pRecordset = NULL; if (m_pConnection->State) { m_pConnection->Close(); } m_pConnection = NULL;