為什麼連接不上數據庫

jxhql 2003-10-19 08:42:45
最近我做了一個類,目的是將連接數據庫的連接字符保存在一二進制文件中,其中部份代碼如下,請各位高手指點:
問題:
1.成員函數TestConnect()中的”m_strConnect==NULL”在沒有對字符串復值時,不出錯,但在執行ConnectSet()后,此語句出錯;
2.在執行ConnectSet()后,執行SaveToFile()將m_strConnect保至文件中,用Notepad打開文件,發現是文件文件,不是二進制文件.里面的內容一目了然.
3.在執行ConnectSet()后,執行TestConnect()函數,連接數據庫成功.如果用GetFromFile()從文件中取得m_strConnect,執行TestConnect()連接數據庫失敗.

void CALAdo::ConnectSet()  //Create connect String;
{
HRESULT hr;
IDataSourceLocatorPtr pDataSource;
try
{
hr=pDataSource.CreateInstance(__uuidof(DataLinks));
if(FAILED(hr))
throw(_com_error(hr,NULL));
m_pConnection=pDataSource->PromptNew();
if(m_pConnection==NULL)
return;
m_strConnect.Format(_T(m_pConnection->GetConnectionString()));
}
catch(_com_error e)
{
AfxMessageBox(e.ErrorMessage());
}
}

BOOL CALAdo::TestConnect() //Test Connect with connect string;
{
/*
if(m_strConnect ==NULL)
{
AfxMessageBox(_T("Connect String is Empty"));
return FALSE;
}
*/
try
{
if(Open(m_strConnect))
{
AfxMessageBox(_T("Connection Success!"));
Close();
}
}
catch(_com_error e)
{
AfxMessageBox(e.ErrorMessage());
}
return true;
}

BOOL CALAdo::SaveToFile() //save connect string to a file;
{

CFile f;
BOOL bResult;
bResult=f.Open("LinkSet.set",CFile::modeCreate|CFile::modeWrite|CFile::typeBinary);
if(!bResult)
return FALSE;
f.Write(m_strConnect,strlen(m_strConnect));
f.Close();
return TRUE;
}

void CALAdo::GetFromFile() //Get connect string form a file;
{
CFile f("LinkSet.set",CFile::shareDenyWrite|CFile::modeRead);
DWORD dwLen=f.GetLength();
f.Read(m_strConnect.GetBuffer(dwLen),dwLen);
f.Close();
}
...全文
44 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
jxhql 2003-10-19
  • 打赏
  • 举报
回复
thank AkiraChing very much!
但從GetFromFile()取得的m_strConnect仍無法連接上數據庫.
AkiraChing 2003-10-19
  • 打赏
  • 举报
回复
1、CALAdo::GetFromFile() 中调用完m_strConnect.GetBuffer后没有m_strConnect.ReleaseBuffer。
2、SaveToFile() 中
bResult=f.Open"LinkSet.set",CFile::modeCreate|CFile::modeWrite|CFile::typeBinary); CFile::typeBinary只在CFile的派生类中使用。
3、ConnectSet()中m_strConnect.Format(_T(m_pConnection->GetConnectionString()));
改成m_strConnect=(LPCTSTR)m_pConnection->GetConnectionString();

4,011

社区成员

发帖
与我相关
我的任务
社区描述
VC/MFC 数据库
社区管理员
  • 数据库
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧