MFC ADO操作Access

#include <afxdtctl.h>
#include <iostream.h>
#import "C:\Program Files\Common Files\System\ADO\msado15.dll" \
	no_namespace rename("EOF", "adoEOF")

int main(int argc, char* argv[])
{
	CoInitialize(NULL);
	//初始化COM库
	AfxOleInit();
	// 定义ADO连接、命令、记录集变量指针
	_ConnectionPtr pConnection;
	_CommandPtr pCommand;
	_RecordsetPtr pRecordSet;
	char* userName;
	char* password;

	// 创建Connection对象
	HRESULT hr = pConnection.CreateInstance("ADODB.Connection");
	if (SUCCEEDED(hr))
	{
		try
		{
		// 打开数据库连接
		hr = pConnection->Open("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=.\\test.mdb","","",adModeUnknown);
		// 创建RecordSet
		pRecordSet.CreateInstance("ADODB.Recordset");
		pRecordSet->Open("SELECT * FROM user1", pConnection.GetInterfacePtr(), adOpenDynamic, adLockOptimistic, adCmdText);

		_variant_t varName, varPassword;
		while(!pRecordSet->adoEOF)
		{
			varName = pRecordSet->GetCollect("name");
			varPassword = pRecordSet->GetCollect("password");
			if(varName.vt != NULL)
			{
				 userName = _com_util::ConvertBSTRToString((_bstr_t)varName);
			}
			if(varPassword.vt != NULL)
			{
				 password = _com_util::ConvertBSTRToString((_bstr_t)varPassword);
			}
			cout << "用户名:" << userName << endl;
			cout << "密码:" << password << endl;
			pRecordSet->MoveNext();
		}

		pConnection->Close();
		}
		catch(_com_error e)
		{
			cout<<e.ErrorMessage();
			cout<<e.Description();
		}
	}
}

 太坑爹了,如果把表名命名为user,Access中执行是不报错的,但在程序中将会出错,错误信息为:子句语法错误。将表名改成其他的就可以了。。。

你可能感兴趣的:(Access)