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