• 在MFC中连接Sql Server的方法


    在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"

  • 相关阅读:
    POJ 2031 Building a Space Station
    [Codeforces 623A] Graph and String
    [Codeforces 986E] Prince's Problem
    [Codeforces 496E] Distributing Parts
    [Codeforces 1037E] Trip
    [Codeforces 1037D] Valid BFS?
    [Codeforces 666B] World Tour
    [Codeforces 449B] Jzzhu and Cities
    [Codeforces 475B] Strongly Connected City
    [Codeforces 437C] The Child and Toy
  • 原文地址:https://www.cnblogs.com/ost/p/680680.html
Copyright © 2020-2023  润新知