mfc中用这段代码连接数据库:
CoInitialize(NULL);_ConnectionPtr pConn(__uuidof(Connection));_RecordsetPtr pRst(__uuidof(Recordset)); pConn->ConnectionString="Data Source=PC-200909161423\MYDATABASE;Initial Catalog=myprogram;User ID=sa";//执行下面这句时就报错“fwq.exe 中的 0x7c812afb 处未处理的异常: Microsoft C++ 异常: 内存位置 0x0012f278 处的 _com_error。”请问这是怎么回事呢?pConn->Open("","","123456",adConnectUnspecified);pRst=pConn->Execute("select * from student",NULL,adCmdText);
CoInitialize(NULL);_ConnectionPtr pConn(__uuidof(Connection));_RecordsetPtr pRst(__uuidof(Recordset)); pConn->ConnectionString="Data Source=PC-200909161423\MYDATABASE;Initial Catalog=myprogram;User ID=sa";//执行下面这句时就报错“fwq.exe 中的 0x7c812afb 处未处理的异常: Microsoft C++ 异常: 内存位置 0x0012f278 处的 _com_error。”请问这是怎么回事呢?pConn->Open("","","123456",adConnectUnspecified);pRst=pConn->Execute("select * from student",NULL,adCmdText);
http://blog.csdn.net/pengzhixi/archive/2009/05/13/4177236.aspx在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"