VC ADO方式读取数据库

本文介绍了一个使用Visual C++和ADO技术查询Access数据库的具体实现过程。通过示例代码展示了如何连接Access数据库,执行SQL查询语句并读取结果集。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

程序环境:数据库名为data.mdb,其中有一个admin表,字段为username,password

程序功能是查询admin表中所有数据,并显示出来

#import "c:/program files/common files/system/ado/msado15.dll" no_namespace rename("EOF","adoEOF")   //导入ADO库
#include<windows.h> 
#include<stdio.h>  

void   main()  
{  
	try  
	{  
		LPCTSTR   DatabaseFile="data.mdb";  
		WIN32_FIND_DATA wfd;  
		HANDLE hFile=FindFirstFile(DatabaseFile,&wfd);  
		if(hFile==INVALID_HANDLE_VALUE)  
		{  
			printf("Cannot Find the database file\n");  
			system("pause");  
			return;  
		}  
		
		CoInitialize(NULL);  
		HRESULT hr;  
		_ConnectionPtr MyConnection;  
		
		MyConnection.CreateInstance(__uuidof(Connection));  
		hr=MyConnection->Open(_bstr_t("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=data.mdb"),  
			_bstr_t(""),  
			_bstr_t(""),  
			adModeUnknown);  
		if(MyConnection==NULL)  
		{  
			printf("Could not acquire a Connection interface");  
			system("pause");  
			return;  
		}  
		
		_CommandPtr  pCommand;  
		pCommand.CreateInstance(__uuidof(Command));  
		pCommand->ActiveConnection=MyConnection;  
		pCommand->CommandText="select * from admin";  
		
		_RecordsetPtr  pRecordset;  
		pRecordset.CreateInstance(__uuidof(Recordset));  
		pRecordset->CursorLocation   =   adUseClient;  
		pRecordset->Open((IDispatch*)pCommand,  
			vtMissing,  
			adOpenStatic,  
			adLockBatchOptimistic,  
			adCmdUnknown);  
		
		_variant_t column;  
		while(!pRecordset->adoEOF)  
		{  
			column=pRecordset->GetCollect("username");  
			if(column.vt   !=   VT_NULL)  
				printf((char*)_bstr_t(column));  
			printf("/t");  
			column=pRecordset->GetCollect("password");  
			if(column.vt   !=   VT_NULL)  
				printf((char*)_bstr_t(column));  
			printf("\n");  
			pRecordset->MoveNext();  
			
		}  
		
		printf("hello world!\n");  
		MyConnection->Close();  
		system("pause");  
		CoUninitialize();  
	}  
	catch(_com_error   &e)  
	{  
		_bstr_t bstrError(e.ErrorMessage());  
		LPTSTR   strError=(char*)bstrError;  
		printf(strError);  
		printf("\n");
		
		system("pause");  
	} 
} 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值