我建了以个基于对话框的应用程序,目的是对Access中的某个通讯录表进行查询,插入,删除等操作,主对话框中有相应的功能菜单项,点击相应的菜单弹出相应的对话框处理;对话框上有查询,删除,更新等菜单项,因为这些功能都会对数据库进行访问,所以我就没有在主对话框的OnInitDialog()和InitInstance()函数中进行连接数据库的初始化和连接,而是在各个弹出对话框的相应函数中进行这些工作,由于自认为这些对话框之间对数据库进行初始化和连接工作互不影响,所以各自的代码基本上是相同的,
但是我发现在有的弹出对话框中对数据库操作会产生错误,不知大侠们对我的做法有啥意见呢???????????????
但是我发现在有的弹出对话框中对数据库操作会产生错误,不知大侠们对我的做法有啥意见呢???????????????
在对话框应用程序(APP)中添加公共成员:_ConnectionPtr m_pConnection;
在其InitInstance()函数中添加:
AfxOleInit();
HRESULT hr;
try
{
hr =m_pConnection.CreateInstance("ADODB.Connection");//创建Connection对象
if(SUCCEEDED(hr))
{
hr=m_pConnection->Open("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=G:\\数据源\\通讯录.mdb","","",adModeUnknown);
///连接数据库
}
catch(_com_error &e)
{
CString str;
str.Format("创建数据源失败!\r\n错误信息:%s",e.ErrorMessage());
AfxMessageBox(str);
printf("Error:\n");
printf("Code=%08lx\n",e.Error());
printf("Meaning=%s\n",e.ErrorMessage());
printf("Source=%s\n",(LPCSTR)e.Source());
printf("Description=%s\n",(LPCSTR)e.Description());
} 然后在菜单相应对话框类中添加:_RecordsetPtr m_pRecordset;
然后按下该对话框的添加按钮,代码如下:
UpdateData(true);
m_pRecordset.CreateInstance("ADODB.Recordset");
CString str;
str.Format("insert into new1(姓名,传呼) values ('%s','%s');",m_name,m_chuanhu);
_bstr_t str1=str;
_variant_t ra;
m_pRecordset->Open(str1,_variant_t((IDispatch*theApp.m_pConnection,true),adOpenDynamic,adLockOptimistic,adCmdText);运行时会出错,发现是执行Open函数时的问题??????????????????????????