c语言读写access数据库
更多文章...

以前的程序中用到的,记录下来做个备份。
1、import com库

#import "c:\program files\common files\system\ado\msado15.dll" no_namespace rename ("EOF", "adoEOF")


2、初始化调用接口

	_ConnectionPtr	pConnection;
	_RecordsetPtr	m_pRecordset;

	CoInitialize(NULL);
	pConnection.CreateInstance(__uuidof(Connection));
	try{	
		pConnection->Open("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=数据库绝对地址","","",adModeUnknown);
	}
	catch(_com_error e){
		CoUninitialize();
		return FALSE;
	}     
	m_pRecordset.CreateInstance(__uuidof(Recordset));



3、执行sql语句

	m_pRecordset->Open("sql语句",
			pConnection.GetInterfacePtr(),	 
			adOpenDynamic, //或adOpenForwardOnly
			adLockOptimistic,
			adCmdText);



4、读取数据


    if(!m_pRecordset->BOF){

        m_pRecordset->MoveFirst();

	while(!m_pRecordset->adoEOF)
        {


        //读取int
	_variant_t var =m_pRecordset->GetCollect("字段名");
	int vi=(long)var;

        //读取字符串
	_variant_t var =m_pRecordset->GetCollect("字段名");
	_bstr_t varbstr=_bstr_t(var);
	char *vs=(LPTSTR)varbstr;


	m_pRecordset->MoveNext();

       }

       }




5、修改和插入数据
	m_pRecordset->PutCollect("字段名",_variant_t(值));
	//...
	m_pRecordset->Update();


        如果插入新的一行则先调用:
	m_pRecordset->AddNew();




6、结束本次sql
	m_pRecordset->Close();




7、释放接口
	if (pConnection)
		if (pConnection->State == adStateOpen)
			pConnection->Close();
	pConnection= NULL;   	
	CoUninitialize();





© time.org.cn