总结如下:
1、在导入ADO库时,在stdafx.h的最后插入语句:
#import "c:\program files\common files\system\ado\msado15.dll" named_guids rename_namespace("ADOCG") rename("EOF", "EndOfFile") rename("BOF","FirstOfFile")
using namespace ADOCG;
#include "icrsint.h"
2、数据库连接字符串最好使用绝对路径
strCon.Format(L"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=%s",L"D:\\VCplusProject\\CommodityDB.mdb");
3、SQL语句中的字段注意不能跟系统保留字冲突,最好都加上中括号,如
pRst=pConn->Execute("select * from [Table]",NULL,adCmdText);
如果Table没有中括号就会报错
4、获取RecordSet中数据时,要保证列名正确,否则编译没问题,但是运行会报错,如
((CListBox*)GetDlgItem(IDC_LIST1))->InsertString(-1,(_bstr_t)pRst->Fields->GetItem(L"Commoditys")->Value);
我就是因为Commoditys写成了Commodity,找错误找的快抓狂了。
5、完整连接代码如下
//操作数据库
CoInitialize(NULL);
_ConnectionPtr pConn(__uuidof(Connection));
_RecordsetPtr pRst(__uuidof(Recordset));
_CommandPtr pCmd(__uuidof(Command));
CString strCon;
strCon.Format(L"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=%s",L"D:\\VCplusProject\\CommodityDB.mdb");
pConn->ConnectionString=_bstr_t(strCon);
pConn->Open("","","",adModeUnknown);
pRst=pConn->Execute("select * from [Table]",NULL,adCmdText);
while(!pRst->EndOfFile)
{
((CListBox*)GetDlgItem(IDC_LIST1))->InsertString(-1,(_bstr_t)pRst->Fields->GetItem(L"Commoditys")->Value);
pRst->MoveNext();
}
pRst->Close();
pConn->Close();
pCmd.Release();
pRst.Release();
pConn.Release();
CoUninitialize();
6、如果只做插入操作,则更简单一些,代码如下
- CoInitialize(NULL);
- _ConnectionPtr pConn(__uuidof(Connection));
- _RecordsetPtr pRst(__uuidof(Recordset));
- _CommandPtr pCmd(__uuidof(Command));
- CString strCon;
- strCon.Format(L"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=%s",L"D:\\VCplusProject\\CommodityDB.mdb");
- pConn->ConnectionString=_bstr_t(strCon);
- pConn->Open("","","",adModeUnknown);
- CString strInsert;
- strInsert.Format(L"INSERT INTO [Table](Commoditys) VALUES ('%s')",strRandItems);
- _variant_t RecordsAffected;
- pConn->Execute(_bstr_t(strInsert),&RecordsAffected,adCmdText);
- pConn->Close();
- pCmd.Release();
- pConn.Release();
- CoUninitialize();