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