我在一个工程中使用ADO访问SQL SERVER2000,步骤如下:
1、在stdafx.h中加入
#import "c:\program files\common files\system\ado\msado15.dll" 
no_namespace rename("EOF","adoEOF")
2、在应用程序头文件中声明:
public:    
_ConnectionPtr m_pConnection;
3、在InitInstance()中加入初始化OLE/COM和连接数据库的智能指针
// 初始化OLE/COM环境
if( !AfxOleInit() )
{
    AfxMessageBox( "OLE初始化失败!");
    return FALSE;
}

// 连接数据库
HRESULT hr;
try
{
hr = m_pConnection.CreateInstance("ADODB.Connection"); // 创建Connection对象
if(SUCCEEDED(hr))
{
hr = m_pConnection->Open("Data Source=sqltst;UID=sa;PWD=dalian8dela","","",adModeUnknown);
AfxMessageBox("数据库已连接");
}
}
catch(_com_error e) // 捕捉异常
{
CString errormessage;
errormessage.Format("连接数据库失败!\r\n错误信息:%s",e.ErrorMessage());
AfxMessageBox(errormessage);///显示错误信息
return FALSE;

4、在另一个类中调用m_pConnection
CString csInsert;
csInsert.Format("INSERT INTO t_TagData (TagNum,OutGo) VALUES(%S,0)",log);
theApp.m_pConnection->Execute((LPCTSTR)csInsert,NULL,adCmdText); //theApp是应用程序实例数据库连接没有问题。
编译出现以下错误:
error C2065: 'theApp' : undeclared identifier
我是vc初学者,既然theApp是应用程序实例,为什么它的公有成员m_pConnection不能被访问呢?
还是我理解有错啊?
焦急等待中。谢谢各位!

解决方案 »

  1.   

    你还是要用afxGetApp来获得的,这个问题前几天还看到有人问过
    虽然theApp是应用程序实例是你的应用程序实例,但是在你的那个自己的类的头文件中没有申明,所以不能这么用可以在使用前
    extern CxxApp theApp;然后再调用
    或者,我更喜欢用::afxGetApp()->m_pConnection->Execute((LPCTSTR,csInsert,NULL,adCmdText); 这么调用
      

  2.   

    你说的正是问题所在,但是我两种方法用的时候出现了以下错误
    第一种办法:在调用theApp的类所在的cpp文件开头加入:
    extern CxxApp theApp;
    编译之后,出现语法错误:syntax error:missing ';'before identifier 'theApp'
    第二种办法:用afxGetApp()
    出现编译错误:m_pConnection is not the member of CWinApp这又如何是好呢?
    谢谢了!
      

  3.   

    补充:
    我是在CxxApp类的头文件中声明m_pConnection的。
      

  4.   

    在stdafx.h中间定义theApp ((CxxApp *)AfxGetApp())再使用吧
      

  5.   

    嗯,嗯,这个好办,CMyApp * p=NULL;
    p = (CMyApp *)AfxGetApp();p->m_pConnection->Execute …………就这样好了,呵呵
      

  6.   

    谢谢各位高手的帮助!
    原问题已经解决.但是一个新的,可怕的错误发生了!!!
    那就是我在网上搜索到的、很多人也碰到了的、还没有找到真正答案的问题:
    我ADO所有的该上的都上了,可是发生编译错误:
    error C2146: syntax error : missing ';' before identifier 'm_pConnection'
    error C2501: '_ConnectionPtr' : missing storage-class or type specifiers
    error C2501: 'm_pConnection' : missing storage-class or type specifiers我搜索得到网上很多帖子都在问这个问题,但至今还没有找到正确答案。期待中……上帝啊,这怎么能让一个初学者遇到这个问题呢
      

  7.   

    出错在_ConnectionPtr m_pConnection;这句上.
    该句在CxxApp类的头文件中被声明。
      

  8.   

    网上搜索得到的类似错误帖子:
    http://www.jxcn.cn/so/cnstu/3921/3921253.htm
    http://www.unix123.com/oiuoiu/xukhmcnpcr/455879.htm
      

  9.   

    晕,还真是错在了这里,不会啊,很难理解,就是这么做的啊,怎么会错呢把那个import换成#import "c:\program files\common files\system\ado\msado15.dll"  
                no_namespace  rename("EOF","adoEOF") rename("BOF","adoBOF")试试呢