MFC连接数据库

 

在MFC中,主要有两种方法可以连接sql数据库
1.利用ADO连接:
#import "msado15.dll" no_namespace rename("EOF", "EndOfFile")
//必须import这个dll,这个文件通常放在C:/Program Files/Common Files/System/ado路径下.
_ConnectionPtr m_ptrConnection; //数据库连接对象
构造函数中添加如下语句
m_ptrConnection = NULL;
 ::CoInitialize(NULL);
//连接数据库的主要代码
BOOL DataVisitor::ConnectDataBase(_bstr_t connectionStr)
{
 /*
 Added by stone. If IDOConnection has not been set up,then create one.
 */
 if(m_ptrConnection == NULL)
 {
  HRESULT hr = m_ptrConnection.CreateInstance(__uuidof(Connection));
  if (FAILED(hr))
  {
   return FALSE;
  }
  else
  {
   _bstr_t strConnect = connectionStr;
   //"Provider=SQLOLEDB;Server=(local);Database=navigation; uid=sa; pwd=3277625;";

   m_ptrConnection->CursorLocation = adUseClient;
   m_ptrConnection->IsolationLevel = adXactReadCommitted;
   try
   {
    m_ptrConnection->Open(strConnect,"","",adModeUnknown);
    return TRUE;
   }
   catch (_com_error e)
   {
   // AfxMessageBox((char *)e.Description());
    return FALSE;
   }
   
  }
 }
 return TRUE;
}


2. 利用ODBC连接
#include <afxdao.h>
CDaoDatabase   *MyDataBase;

BOOL MyDB_OperSqL::Open_MyDatabase(CString connstr)
{
 try
 {
  if (MyDataBase == NULL)
  {
   MyDataBase = new CDaoDatabase();
  }
  MyDataBase->Open(NULL,0,0,connstr);

 }
 catch( CDaoException* e )
 {
  CString message = _T("MyDB_OperSqL 数据库异常:  ");     
  message += e->m_pErrorInfo->m_strDescription;
  char info[400];
  sprintf(info,message);
  DispErrorMessage(info,__LINE__);
  e->Delete( );
  return FALSE;
 }
 catch (CMemoryException *e)
 {
  DispErrorMessage("MyDB_OperSqL 内存异常!",__LINE__);
  e->Delete( );
  return FALSE;
 }
 catch(...)
 {
  DispErrorMessage("MyDB_OperSqL 其它异常!",__LINE__);
  return FALSE;
 }
 return  TRUE;
}
这里的连接字符串connstr一般是如下内容
"ODBC;DRIVER={SQL Server};SERVER=(local);DATABASE=yourDataBase;UID=yourID;PWD=yourPassword"

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值