hr=m_pConnection->Open("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=test.mdb"," "," ",adModeUnknown); //连接数据库
以为我的数据库是放在d盘根目录下所以稍作修改:Data Source=D:\test.mdb
但是运行时老显示错误:Failed to connect with database!Error message:IDispatch error #3146
我想知道:1,书上说上面字符串中的Provider是针对Access2000的,不知道2003是不是也这样写?
2.不知道路径这样写对不对?
3.上面字符串中的"","",表示用户名和密码,请问是我登陆计算机时的用户名和密码还是我建的数据库的用户名和密码?
问题可能有点幼稚,不过 ... 我真的是不明白 !!
谢谢高手指点!!
13 个解决方案
#1
把数据库文件放到你的工程目录下试试看。
#2
第一、路径应为 d:\\test.mdb 而不是 d:\test.mdb
第二、连接字符串如果不行,则用用我的:
hr=m_pConnection->Open("Provider=Microsoft.Jet.OLEDB.4.0;Password=admin;Data Source=d:\\test.mdb;Persist Security Info=True"," "," ",adModeUnknown); //连接数据库
第二、连接字符串如果不行,则用用我的:
hr=m_pConnection->Open("Provider=Microsoft.Jet.OLEDB.4.0;Password=admin;Data Source=d:\\test.mdb;Persist Security Info=True"," "," ",adModeUnknown); //连接数据库
#3
上面两位提到的方法我都用了 还是不行啊!
我都快被他气晕了:(
我都快被他气晕了:(
#4
如果是单纯操作ADO.MSSQL
可以参考以下的类
用以下的类试一试:
引用msado15.tlh
.H 文件
class CMyDataBase
{
public:
int GetRecordCount(int& nCount);
bool ExecuteSQL(CString& strSQL);
void InitDBParam(CString sHost, CString sDBName, CString sUID, CString sPWD);
void CloseDB();
bool OpenDB();
bool IsConnectedValid();
CMyDataBase();
virtual ~CMyDataBase();
bool GetMTmsg(CMTMsg& Mtmsg);
bool SetMtmsgFlag(int iId, int iStatus);
bool MoveMtmsgToBak(int iId);
private:
void dmpCOMerr(_com_error &e, int line, char *file, bool traceOnly);
bool m_bConn;
void TrimStr(CString &sStr);
// 数据库参数
CString m_sDBHost; //数据库服务器名
CString m_sDBName; //数据库名
CString m_sUID; //数据库用户名
CString m_sPWD; //数据库密码
CString m_sConn;
_ConnectionPtrm_pConn;
};
cpp文件
#include "stdafx.h"
#include "MyDataBase.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
/*===========================================================================
*常用的宏
===========================================================================*/
inline void TESTHR(HRESULT x) {if FAILED(x) _com_issue_error(x);};
void PrintProviderError(_ConnectionPtr pConnection);
void PrintComError(_com_error &e);
//设置存储过程参数
#define PutPARA(pCom, name, value) (pCom)->Parameters->GetItem(_variant_t(name))->PutValue(value)
//取得存储过程参数
#define GetPARA(pCom, name) (pCom)->Parameters->GetItem(_variant_t(name))->Value
//取记录中指定字段参数
#define GetVALUE(mRs ,name) (mRs)->Fields->Item[(_variant_t(name))]->Value
//取记录中指定字段参数,并转换为CString
#define GetSTRVALUE(mRs, name) CString((mRs)->Fields->Item[(_variant_t(name))]->Value.bstrVal).GetBuffer(0)
#define RSGetVALUE(x) (_bstr_t(pRs->GetCollect(x)))
#define DMPcomERR(e) dmpCOMerr(e,__LINE__,__FILE__, true);
//#define CREATEiNSTANCE(sp, riid) { HRESULT _hr = sp.CreateInstance(__uuidof(riid)); if (FAILED(_hr)) _com_issue_error(_hr); }
//========================================================================
#include "io.h"
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CMyDataBase::CMyDataBase()
{
m_bConn = false;
}
CMyDataBase::~CMyDataBase()
{
CloseDB();
}
void CMyDataBase::dmpCOMerr(_com_error &e, int line, char *file, bool traceOnly)
{
CString ErrMsg;
ErrMsg.Format(" Line: %d File %s", line, file);
_bstr_t bstrSource(e.Source());
_bstr_t bs = _bstr_t(" Error: ") + _bstr_t(e.Error()) + _bstr_t(" Msg: ")
+ _bstr_t(e.ErrorMessage()) + _bstr_t(" Description: ")
+ _bstr_t(e.Description()) + _bstr_t(ErrMsg) ;
if(!traceOnly)
MessageBox(0,bs,bstrSource, MB_OK);
ErrMsg.Format("%s %s \n", (char *) bs, (char *) bstrSource);
}
bool CMyDataBase::IsConnectedValid()
{
if (!m_bConn)
return false;
try
{
m_pConn->Execute(L"select top 1 * from sysobjects", NULL, adOptionUnspecified);
}
catch (_com_error&)
{
m_bConn = false;
return false;
}catch(...){}
return true;
}
bool CMyDataBase::OpenDB()
{
if (m_bConn)
return true;
try
{
CoInitialize(NULL);
m_pConn.CreateInstance(__uuidof(Connection));
m_pConn->ConnectionString = _bstr_t(m_sConn);
m_pConn->Open("", "", "", adConnectUnspecified);
m_bConn = true;
}
catch (_com_error& e)
{
m_bConn = false;
//DMPcomERR(e);`
return false;
}
catch (...)
{
return false;
}
return true;
}
void CMyDataBase::CloseDB()
{
if (m_bConn)
{
try
{
m_pConn->Close();
}
catch (...)
{
}
m_bConn = false;
}
CoUninitialize();
}
void CMyDataBase::TrimStr(CString &sStr)
{
sStr.TrimLeft();
sStr.TrimRight();
}
void CMyDataBase::InitDBParam(CString sHost, CString sDBName, CString sUID, CString sPWD)
{
m_sDBHost = sHost;
m_sDBName = sDBName;
m_sUID = sUID;
m_sPWD = sPWD;
m_sConn="Provider=Microsoft.Jet.OLEDB.4.0;Password=admin;Data Source=d:\\test.mdb;Persist Security Info=True";
//m_sConn.Format("driver={sql server};server=%s;Database=%s;UID=%s;PWD=%s;",
m_sDBHost, m_sDBName, m_sUID, m_sPWD);
}
bool CMyDataBase::ExecuteSQL(CString& strSQL)
{
if (!OpenDB())
return false;
try
{
_CommandPtr pCmd;
_RecordsetPtr pRs;
TESTHR(pCmd.CreateInstance(__uuidof(Command)));
TESTHR(pRs.CreateInstance(__uuidof(Recordset)));
pCmd->ActiveConnection = m_pConn;
pCmd->CommandText = _bstr_t(strSQL);
pCmd->CommandType = adCmdText;
pCmd->Parameters->Refresh();
pRs = pCmd->Execute(NULL, NULL, adCmdText);
if (pRs->GetState() != adStateClosed)
pRs->Close();
pRs.Release();
pCmd.Release();
}
catch (_com_error& e)
{
m_bConn = false;
DMPcomERR(e);
#ifdef _DEBUG
OutputDebugString(strSQL);
#endif
return false;
}
catch(...)
{
#ifdef _DEBUG
OutputDebugString(strSQL);
#endif
return false;
}
return true;
}
bool CMyDataBase::GetMTmsg(CMTMsg& Mtmsg)
{
Mtmsg.Reset();
if (!OpenDB())
return false;
CString strSQL;
try
{
_CommandPtr pCmd;
_RecordsetPtr pRs;
TESTHR(pCmd.CreateInstance(__uuidof(Command)));
TESTHR(pRs.CreateInstance(__uuidof(Recordset)));
strSQL.Format("%s", "select top 1 * from sms_send where status = 0 ");
pCmd->ActiveConnection = m_pConn;
pCmd->CommandText = _bstr_t(strSQL);
pCmd->CommandType = adCmdText;
pCmd->Parameters->Refresh();
pRs = pCmd->Execute(NULL, NULL, adCmdText);
if (!pRs->adoEOF)
{
Mtmsg.m_iId = atoi((LPTSTR)RSGetVALUE(L"Id"));
Mtmsg.m_strMobile = (LPTSTR)RSGetVALUE(L"Mobile");
Mtmsg.m_strContent = (LPTSTR)RSGetVALUE(L"content");
Mtmsg.m_strEId = (LPTSTR)RSGetVALUE(L"Eid");
pRs->MoveNext();
}
if (pRs->GetState() != adStateClosed)
pRs->Close();
pRs.Release();
pCmd.Release();
}
catch (_com_error& e)
{
m_bConn = false;
DMPcomERR(e);
#ifdef _DEBUG
OutputDebugString(strSQL);
#endif
return false;
}
catch(...)
{
//LOG();
#ifdef _DEBUG
OutputDebugString(strSQL);
#endif
return false;
}
return true;
}
bool CMyDataBase::SetMtmsgFlag(int iId, int iStatus)
{
CString strSQL;
strSQL.Format("update sms_send set status = %d where id = %d", iStatus, iId);
return ExecuteSQL( strSQL );
}
bool CMyDataBase::MoveMtmsgToBak(int iId)
{
CString strSQL;
strSQL.Format("insert into sms_Already_send select * from sms_send where id = %d", iId);
if(ExecuteSQL( strSQL ))
{
strSQL.Format("delete sms_send where id = %d", iId);
return ExecuteSQL( strSQL );
}
return false;
}
------
执行SQL参看:ExecuteSQL
取数据参考:GetMTmsg
可以参考以下的类
用以下的类试一试:
引用msado15.tlh
.H 文件
class CMyDataBase
{
public:
int GetRecordCount(int& nCount);
bool ExecuteSQL(CString& strSQL);
void InitDBParam(CString sHost, CString sDBName, CString sUID, CString sPWD);
void CloseDB();
bool OpenDB();
bool IsConnectedValid();
CMyDataBase();
virtual ~CMyDataBase();
bool GetMTmsg(CMTMsg& Mtmsg);
bool SetMtmsgFlag(int iId, int iStatus);
bool MoveMtmsgToBak(int iId);
private:
void dmpCOMerr(_com_error &e, int line, char *file, bool traceOnly);
bool m_bConn;
void TrimStr(CString &sStr);
// 数据库参数
CString m_sDBHost; //数据库服务器名
CString m_sDBName; //数据库名
CString m_sUID; //数据库用户名
CString m_sPWD; //数据库密码
CString m_sConn;
_ConnectionPtrm_pConn;
};
cpp文件
#include "stdafx.h"
#include "MyDataBase.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
/*===========================================================================
*常用的宏
===========================================================================*/
inline void TESTHR(HRESULT x) {if FAILED(x) _com_issue_error(x);};
void PrintProviderError(_ConnectionPtr pConnection);
void PrintComError(_com_error &e);
//设置存储过程参数
#define PutPARA(pCom, name, value) (pCom)->Parameters->GetItem(_variant_t(name))->PutValue(value)
//取得存储过程参数
#define GetPARA(pCom, name) (pCom)->Parameters->GetItem(_variant_t(name))->Value
//取记录中指定字段参数
#define GetVALUE(mRs ,name) (mRs)->Fields->Item[(_variant_t(name))]->Value
//取记录中指定字段参数,并转换为CString
#define GetSTRVALUE(mRs, name) CString((mRs)->Fields->Item[(_variant_t(name))]->Value.bstrVal).GetBuffer(0)
#define RSGetVALUE(x) (_bstr_t(pRs->GetCollect(x)))
#define DMPcomERR(e) dmpCOMerr(e,__LINE__,__FILE__, true);
//#define CREATEiNSTANCE(sp, riid) { HRESULT _hr = sp.CreateInstance(__uuidof(riid)); if (FAILED(_hr)) _com_issue_error(_hr); }
//========================================================================
#include "io.h"
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CMyDataBase::CMyDataBase()
{
m_bConn = false;
}
CMyDataBase::~CMyDataBase()
{
CloseDB();
}
void CMyDataBase::dmpCOMerr(_com_error &e, int line, char *file, bool traceOnly)
{
CString ErrMsg;
ErrMsg.Format(" Line: %d File %s", line, file);
_bstr_t bstrSource(e.Source());
_bstr_t bs = _bstr_t(" Error: ") + _bstr_t(e.Error()) + _bstr_t(" Msg: ")
+ _bstr_t(e.ErrorMessage()) + _bstr_t(" Description: ")
+ _bstr_t(e.Description()) + _bstr_t(ErrMsg) ;
if(!traceOnly)
MessageBox(0,bs,bstrSource, MB_OK);
ErrMsg.Format("%s %s \n", (char *) bs, (char *) bstrSource);
}
bool CMyDataBase::IsConnectedValid()
{
if (!m_bConn)
return false;
try
{
m_pConn->Execute(L"select top 1 * from sysobjects", NULL, adOptionUnspecified);
}
catch (_com_error&)
{
m_bConn = false;
return false;
}catch(...){}
return true;
}
bool CMyDataBase::OpenDB()
{
if (m_bConn)
return true;
try
{
CoInitialize(NULL);
m_pConn.CreateInstance(__uuidof(Connection));
m_pConn->ConnectionString = _bstr_t(m_sConn);
m_pConn->Open("", "", "", adConnectUnspecified);
m_bConn = true;
}
catch (_com_error& e)
{
m_bConn = false;
//DMPcomERR(e);`
return false;
}
catch (...)
{
return false;
}
return true;
}
void CMyDataBase::CloseDB()
{
if (m_bConn)
{
try
{
m_pConn->Close();
}
catch (...)
{
}
m_bConn = false;
}
CoUninitialize();
}
void CMyDataBase::TrimStr(CString &sStr)
{
sStr.TrimLeft();
sStr.TrimRight();
}
void CMyDataBase::InitDBParam(CString sHost, CString sDBName, CString sUID, CString sPWD)
{
m_sDBHost = sHost;
m_sDBName = sDBName;
m_sUID = sUID;
m_sPWD = sPWD;
m_sConn="Provider=Microsoft.Jet.OLEDB.4.0;Password=admin;Data Source=d:\\test.mdb;Persist Security Info=True";
//m_sConn.Format("driver={sql server};server=%s;Database=%s;UID=%s;PWD=%s;",
m_sDBHost, m_sDBName, m_sUID, m_sPWD);
}
bool CMyDataBase::ExecuteSQL(CString& strSQL)
{
if (!OpenDB())
return false;
try
{
_CommandPtr pCmd;
_RecordsetPtr pRs;
TESTHR(pCmd.CreateInstance(__uuidof(Command)));
TESTHR(pRs.CreateInstance(__uuidof(Recordset)));
pCmd->ActiveConnection = m_pConn;
pCmd->CommandText = _bstr_t(strSQL);
pCmd->CommandType = adCmdText;
pCmd->Parameters->Refresh();
pRs = pCmd->Execute(NULL, NULL, adCmdText);
if (pRs->GetState() != adStateClosed)
pRs->Close();
pRs.Release();
pCmd.Release();
}
catch (_com_error& e)
{
m_bConn = false;
DMPcomERR(e);
#ifdef _DEBUG
OutputDebugString(strSQL);
#endif
return false;
}
catch(...)
{
#ifdef _DEBUG
OutputDebugString(strSQL);
#endif
return false;
}
return true;
}
bool CMyDataBase::GetMTmsg(CMTMsg& Mtmsg)
{
Mtmsg.Reset();
if (!OpenDB())
return false;
CString strSQL;
try
{
_CommandPtr pCmd;
_RecordsetPtr pRs;
TESTHR(pCmd.CreateInstance(__uuidof(Command)));
TESTHR(pRs.CreateInstance(__uuidof(Recordset)));
strSQL.Format("%s", "select top 1 * from sms_send where status = 0 ");
pCmd->ActiveConnection = m_pConn;
pCmd->CommandText = _bstr_t(strSQL);
pCmd->CommandType = adCmdText;
pCmd->Parameters->Refresh();
pRs = pCmd->Execute(NULL, NULL, adCmdText);
if (!pRs->adoEOF)
{
Mtmsg.m_iId = atoi((LPTSTR)RSGetVALUE(L"Id"));
Mtmsg.m_strMobile = (LPTSTR)RSGetVALUE(L"Mobile");
Mtmsg.m_strContent = (LPTSTR)RSGetVALUE(L"content");
Mtmsg.m_strEId = (LPTSTR)RSGetVALUE(L"Eid");
pRs->MoveNext();
}
if (pRs->GetState() != adStateClosed)
pRs->Close();
pRs.Release();
pCmd.Release();
}
catch (_com_error& e)
{
m_bConn = false;
DMPcomERR(e);
#ifdef _DEBUG
OutputDebugString(strSQL);
#endif
return false;
}
catch(...)
{
//LOG();
#ifdef _DEBUG
OutputDebugString(strSQL);
#endif
return false;
}
return true;
}
bool CMyDataBase::SetMtmsgFlag(int iId, int iStatus)
{
CString strSQL;
strSQL.Format("update sms_send set status = %d where id = %d", iStatus, iId);
return ExecuteSQL( strSQL );
}
bool CMyDataBase::MoveMtmsgToBak(int iId)
{
CString strSQL;
strSQL.Format("insert into sms_Already_send select * from sms_send where id = %d", iId);
if(ExecuteSQL( strSQL ))
{
strSQL.Format("delete sms_send where id = %d", iId);
return ExecuteSQL( strSQL );
}
return false;
}
------
执行SQL参看:ExecuteSQL
取数据参考:GetMTmsg
#5
看起来好复杂啊!我是初学vc++ 所以看不太懂...~_~
#6
先学会调试,会调试比会一大堆概念重要多了。看看是不是你的m_pConnection的创建是不是有问题,此外,字符串应该以bstr的方式传入
#7
::CoInitialize(NULL);//初始化COM
HRESULT hr=m_pConnection.CreateInstance("ADODB.Connection");
if(SUCCEEDED(hr))
{
try
{
// 打开本地SQL库
//m_pConnection->Open("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Data.mdb;Jet OLEDB:Database Password=","","",adModeUnknown);(accesss数据库,Data.mdb与工程在同一目录下)
m_pConnection->Open("driver={SQL Server};Server=127.0.0.1;DATABASE=netmanage;UID=;PWD=","","",adModeUnknown);
return true;
}
catch(_com_error e)//COM错误取得,当执行COM功能的时候,如果出错,可以捕捉到_com_error的异常
{
CString strComError;
strComError.Format("错误编号: %08lx\n错误信息: %s\n错误源: %s\n错误描述: %s",
e.Error(), // 错误编号
e.ErrorMessage(), // 错误信息
(LPCSTR) e.Source(), // 错误源
(LPCSTR) e.Description()); // 错误描述
::MessageBox(NULL,strComError,"错误",MB_ICONEXCLAMATION);
return FALSE;
}
}
HRESULT hr=m_pConnection.CreateInstance("ADODB.Connection");
if(SUCCEEDED(hr))
{
try
{
// 打开本地SQL库
//m_pConnection->Open("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Data.mdb;Jet OLEDB:Database Password=","","",adModeUnknown);(accesss数据库,Data.mdb与工程在同一目录下)
m_pConnection->Open("driver={SQL Server};Server=127.0.0.1;DATABASE=netmanage;UID=;PWD=","","",adModeUnknown);
return true;
}
catch(_com_error e)//COM错误取得,当执行COM功能的时候,如果出错,可以捕捉到_com_error的异常
{
CString strComError;
strComError.Format("错误编号: %08lx\n错误信息: %s\n错误源: %s\n错误描述: %s",
e.Error(), // 错误编号
e.ErrorMessage(), // 错误信息
(LPCSTR) e.Source(), // 错误源
(LPCSTR) e.Description()); // 错误描述
::MessageBox(NULL,strComError,"错误",MB_ICONEXCLAMATION);
return FALSE;
}
}
#8
还要在STAAFX.H中导入:
#import "C:\Program Files\Common Files\System\ado\msado15.dll" no_namespace rename("EOF","adoEOF")
#import "C:\Program Files\Common Files\System\ado\msado15.dll" no_namespace rename("EOF","adoEOF")
#9
已经解决问题了 呵呵 谢谢各位了!!
#10
楼主我也是这个问题啊 ,你都解决了 ,能不能说下是怎么解决的啊 ??
#11
楼主亮亮解决方法啊 还有一大群我们这初学者也想知道 谢谢
#12
楼主 求解决方法
#13
很有可能是密码的问题,如果你的access数据库有密码,则在open函数中应该加入密码,如:
pConnection->Open("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=JyDB.mdb ;Jet OLEDB:Database Password=jy_agt&pwd ","","",adModeUnknown);
pConnection->Open("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=JyDB.mdb ;Jet OLEDB:Database Password=jy_agt&pwd ","","",adModeUnknown);
#1
把数据库文件放到你的工程目录下试试看。
#2
第一、路径应为 d:\\test.mdb 而不是 d:\test.mdb
第二、连接字符串如果不行,则用用我的:
hr=m_pConnection->Open("Provider=Microsoft.Jet.OLEDB.4.0;Password=admin;Data Source=d:\\test.mdb;Persist Security Info=True"," "," ",adModeUnknown); //连接数据库
第二、连接字符串如果不行,则用用我的:
hr=m_pConnection->Open("Provider=Microsoft.Jet.OLEDB.4.0;Password=admin;Data Source=d:\\test.mdb;Persist Security Info=True"," "," ",adModeUnknown); //连接数据库
#3
上面两位提到的方法我都用了 还是不行啊!
我都快被他气晕了:(
我都快被他气晕了:(
#4
如果是单纯操作ADO.MSSQL
可以参考以下的类
用以下的类试一试:
引用msado15.tlh
.H 文件
class CMyDataBase
{
public:
int GetRecordCount(int& nCount);
bool ExecuteSQL(CString& strSQL);
void InitDBParam(CString sHost, CString sDBName, CString sUID, CString sPWD);
void CloseDB();
bool OpenDB();
bool IsConnectedValid();
CMyDataBase();
virtual ~CMyDataBase();
bool GetMTmsg(CMTMsg& Mtmsg);
bool SetMtmsgFlag(int iId, int iStatus);
bool MoveMtmsgToBak(int iId);
private:
void dmpCOMerr(_com_error &e, int line, char *file, bool traceOnly);
bool m_bConn;
void TrimStr(CString &sStr);
// 数据库参数
CString m_sDBHost; //数据库服务器名
CString m_sDBName; //数据库名
CString m_sUID; //数据库用户名
CString m_sPWD; //数据库密码
CString m_sConn;
_ConnectionPtrm_pConn;
};
cpp文件
#include "stdafx.h"
#include "MyDataBase.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
/*===========================================================================
*常用的宏
===========================================================================*/
inline void TESTHR(HRESULT x) {if FAILED(x) _com_issue_error(x);};
void PrintProviderError(_ConnectionPtr pConnection);
void PrintComError(_com_error &e);
//设置存储过程参数
#define PutPARA(pCom, name, value) (pCom)->Parameters->GetItem(_variant_t(name))->PutValue(value)
//取得存储过程参数
#define GetPARA(pCom, name) (pCom)->Parameters->GetItem(_variant_t(name))->Value
//取记录中指定字段参数
#define GetVALUE(mRs ,name) (mRs)->Fields->Item[(_variant_t(name))]->Value
//取记录中指定字段参数,并转换为CString
#define GetSTRVALUE(mRs, name) CString((mRs)->Fields->Item[(_variant_t(name))]->Value.bstrVal).GetBuffer(0)
#define RSGetVALUE(x) (_bstr_t(pRs->GetCollect(x)))
#define DMPcomERR(e) dmpCOMerr(e,__LINE__,__FILE__, true);
//#define CREATEiNSTANCE(sp, riid) { HRESULT _hr = sp.CreateInstance(__uuidof(riid)); if (FAILED(_hr)) _com_issue_error(_hr); }
//========================================================================
#include "io.h"
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CMyDataBase::CMyDataBase()
{
m_bConn = false;
}
CMyDataBase::~CMyDataBase()
{
CloseDB();
}
void CMyDataBase::dmpCOMerr(_com_error &e, int line, char *file, bool traceOnly)
{
CString ErrMsg;
ErrMsg.Format(" Line: %d File %s", line, file);
_bstr_t bstrSource(e.Source());
_bstr_t bs = _bstr_t(" Error: ") + _bstr_t(e.Error()) + _bstr_t(" Msg: ")
+ _bstr_t(e.ErrorMessage()) + _bstr_t(" Description: ")
+ _bstr_t(e.Description()) + _bstr_t(ErrMsg) ;
if(!traceOnly)
MessageBox(0,bs,bstrSource, MB_OK);
ErrMsg.Format("%s %s \n", (char *) bs, (char *) bstrSource);
}
bool CMyDataBase::IsConnectedValid()
{
if (!m_bConn)
return false;
try
{
m_pConn->Execute(L"select top 1 * from sysobjects", NULL, adOptionUnspecified);
}
catch (_com_error&)
{
m_bConn = false;
return false;
}catch(...){}
return true;
}
bool CMyDataBase::OpenDB()
{
if (m_bConn)
return true;
try
{
CoInitialize(NULL);
m_pConn.CreateInstance(__uuidof(Connection));
m_pConn->ConnectionString = _bstr_t(m_sConn);
m_pConn->Open("", "", "", adConnectUnspecified);
m_bConn = true;
}
catch (_com_error& e)
{
m_bConn = false;
//DMPcomERR(e);`
return false;
}
catch (...)
{
return false;
}
return true;
}
void CMyDataBase::CloseDB()
{
if (m_bConn)
{
try
{
m_pConn->Close();
}
catch (...)
{
}
m_bConn = false;
}
CoUninitialize();
}
void CMyDataBase::TrimStr(CString &sStr)
{
sStr.TrimLeft();
sStr.TrimRight();
}
void CMyDataBase::InitDBParam(CString sHost, CString sDBName, CString sUID, CString sPWD)
{
m_sDBHost = sHost;
m_sDBName = sDBName;
m_sUID = sUID;
m_sPWD = sPWD;
m_sConn="Provider=Microsoft.Jet.OLEDB.4.0;Password=admin;Data Source=d:\\test.mdb;Persist Security Info=True";
//m_sConn.Format("driver={sql server};server=%s;Database=%s;UID=%s;PWD=%s;",
m_sDBHost, m_sDBName, m_sUID, m_sPWD);
}
bool CMyDataBase::ExecuteSQL(CString& strSQL)
{
if (!OpenDB())
return false;
try
{
_CommandPtr pCmd;
_RecordsetPtr pRs;
TESTHR(pCmd.CreateInstance(__uuidof(Command)));
TESTHR(pRs.CreateInstance(__uuidof(Recordset)));
pCmd->ActiveConnection = m_pConn;
pCmd->CommandText = _bstr_t(strSQL);
pCmd->CommandType = adCmdText;
pCmd->Parameters->Refresh();
pRs = pCmd->Execute(NULL, NULL, adCmdText);
if (pRs->GetState() != adStateClosed)
pRs->Close();
pRs.Release();
pCmd.Release();
}
catch (_com_error& e)
{
m_bConn = false;
DMPcomERR(e);
#ifdef _DEBUG
OutputDebugString(strSQL);
#endif
return false;
}
catch(...)
{
#ifdef _DEBUG
OutputDebugString(strSQL);
#endif
return false;
}
return true;
}
bool CMyDataBase::GetMTmsg(CMTMsg& Mtmsg)
{
Mtmsg.Reset();
if (!OpenDB())
return false;
CString strSQL;
try
{
_CommandPtr pCmd;
_RecordsetPtr pRs;
TESTHR(pCmd.CreateInstance(__uuidof(Command)));
TESTHR(pRs.CreateInstance(__uuidof(Recordset)));
strSQL.Format("%s", "select top 1 * from sms_send where status = 0 ");
pCmd->ActiveConnection = m_pConn;
pCmd->CommandText = _bstr_t(strSQL);
pCmd->CommandType = adCmdText;
pCmd->Parameters->Refresh();
pRs = pCmd->Execute(NULL, NULL, adCmdText);
if (!pRs->adoEOF)
{
Mtmsg.m_iId = atoi((LPTSTR)RSGetVALUE(L"Id"));
Mtmsg.m_strMobile = (LPTSTR)RSGetVALUE(L"Mobile");
Mtmsg.m_strContent = (LPTSTR)RSGetVALUE(L"content");
Mtmsg.m_strEId = (LPTSTR)RSGetVALUE(L"Eid");
pRs->MoveNext();
}
if (pRs->GetState() != adStateClosed)
pRs->Close();
pRs.Release();
pCmd.Release();
}
catch (_com_error& e)
{
m_bConn = false;
DMPcomERR(e);
#ifdef _DEBUG
OutputDebugString(strSQL);
#endif
return false;
}
catch(...)
{
//LOG();
#ifdef _DEBUG
OutputDebugString(strSQL);
#endif
return false;
}
return true;
}
bool CMyDataBase::SetMtmsgFlag(int iId, int iStatus)
{
CString strSQL;
strSQL.Format("update sms_send set status = %d where id = %d", iStatus, iId);
return ExecuteSQL( strSQL );
}
bool CMyDataBase::MoveMtmsgToBak(int iId)
{
CString strSQL;
strSQL.Format("insert into sms_Already_send select * from sms_send where id = %d", iId);
if(ExecuteSQL( strSQL ))
{
strSQL.Format("delete sms_send where id = %d", iId);
return ExecuteSQL( strSQL );
}
return false;
}
------
执行SQL参看:ExecuteSQL
取数据参考:GetMTmsg
可以参考以下的类
用以下的类试一试:
引用msado15.tlh
.H 文件
class CMyDataBase
{
public:
int GetRecordCount(int& nCount);
bool ExecuteSQL(CString& strSQL);
void InitDBParam(CString sHost, CString sDBName, CString sUID, CString sPWD);
void CloseDB();
bool OpenDB();
bool IsConnectedValid();
CMyDataBase();
virtual ~CMyDataBase();
bool GetMTmsg(CMTMsg& Mtmsg);
bool SetMtmsgFlag(int iId, int iStatus);
bool MoveMtmsgToBak(int iId);
private:
void dmpCOMerr(_com_error &e, int line, char *file, bool traceOnly);
bool m_bConn;
void TrimStr(CString &sStr);
// 数据库参数
CString m_sDBHost; //数据库服务器名
CString m_sDBName; //数据库名
CString m_sUID; //数据库用户名
CString m_sPWD; //数据库密码
CString m_sConn;
_ConnectionPtrm_pConn;
};
cpp文件
#include "stdafx.h"
#include "MyDataBase.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
/*===========================================================================
*常用的宏
===========================================================================*/
inline void TESTHR(HRESULT x) {if FAILED(x) _com_issue_error(x);};
void PrintProviderError(_ConnectionPtr pConnection);
void PrintComError(_com_error &e);
//设置存储过程参数
#define PutPARA(pCom, name, value) (pCom)->Parameters->GetItem(_variant_t(name))->PutValue(value)
//取得存储过程参数
#define GetPARA(pCom, name) (pCom)->Parameters->GetItem(_variant_t(name))->Value
//取记录中指定字段参数
#define GetVALUE(mRs ,name) (mRs)->Fields->Item[(_variant_t(name))]->Value
//取记录中指定字段参数,并转换为CString
#define GetSTRVALUE(mRs, name) CString((mRs)->Fields->Item[(_variant_t(name))]->Value.bstrVal).GetBuffer(0)
#define RSGetVALUE(x) (_bstr_t(pRs->GetCollect(x)))
#define DMPcomERR(e) dmpCOMerr(e,__LINE__,__FILE__, true);
//#define CREATEiNSTANCE(sp, riid) { HRESULT _hr = sp.CreateInstance(__uuidof(riid)); if (FAILED(_hr)) _com_issue_error(_hr); }
//========================================================================
#include "io.h"
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CMyDataBase::CMyDataBase()
{
m_bConn = false;
}
CMyDataBase::~CMyDataBase()
{
CloseDB();
}
void CMyDataBase::dmpCOMerr(_com_error &e, int line, char *file, bool traceOnly)
{
CString ErrMsg;
ErrMsg.Format(" Line: %d File %s", line, file);
_bstr_t bstrSource(e.Source());
_bstr_t bs = _bstr_t(" Error: ") + _bstr_t(e.Error()) + _bstr_t(" Msg: ")
+ _bstr_t(e.ErrorMessage()) + _bstr_t(" Description: ")
+ _bstr_t(e.Description()) + _bstr_t(ErrMsg) ;
if(!traceOnly)
MessageBox(0,bs,bstrSource, MB_OK);
ErrMsg.Format("%s %s \n", (char *) bs, (char *) bstrSource);
}
bool CMyDataBase::IsConnectedValid()
{
if (!m_bConn)
return false;
try
{
m_pConn->Execute(L"select top 1 * from sysobjects", NULL, adOptionUnspecified);
}
catch (_com_error&)
{
m_bConn = false;
return false;
}catch(...){}
return true;
}
bool CMyDataBase::OpenDB()
{
if (m_bConn)
return true;
try
{
CoInitialize(NULL);
m_pConn.CreateInstance(__uuidof(Connection));
m_pConn->ConnectionString = _bstr_t(m_sConn);
m_pConn->Open("", "", "", adConnectUnspecified);
m_bConn = true;
}
catch (_com_error& e)
{
m_bConn = false;
//DMPcomERR(e);`
return false;
}
catch (...)
{
return false;
}
return true;
}
void CMyDataBase::CloseDB()
{
if (m_bConn)
{
try
{
m_pConn->Close();
}
catch (...)
{
}
m_bConn = false;
}
CoUninitialize();
}
void CMyDataBase::TrimStr(CString &sStr)
{
sStr.TrimLeft();
sStr.TrimRight();
}
void CMyDataBase::InitDBParam(CString sHost, CString sDBName, CString sUID, CString sPWD)
{
m_sDBHost = sHost;
m_sDBName = sDBName;
m_sUID = sUID;
m_sPWD = sPWD;
m_sConn="Provider=Microsoft.Jet.OLEDB.4.0;Password=admin;Data Source=d:\\test.mdb;Persist Security Info=True";
//m_sConn.Format("driver={sql server};server=%s;Database=%s;UID=%s;PWD=%s;",
m_sDBHost, m_sDBName, m_sUID, m_sPWD);
}
bool CMyDataBase::ExecuteSQL(CString& strSQL)
{
if (!OpenDB())
return false;
try
{
_CommandPtr pCmd;
_RecordsetPtr pRs;
TESTHR(pCmd.CreateInstance(__uuidof(Command)));
TESTHR(pRs.CreateInstance(__uuidof(Recordset)));
pCmd->ActiveConnection = m_pConn;
pCmd->CommandText = _bstr_t(strSQL);
pCmd->CommandType = adCmdText;
pCmd->Parameters->Refresh();
pRs = pCmd->Execute(NULL, NULL, adCmdText);
if (pRs->GetState() != adStateClosed)
pRs->Close();
pRs.Release();
pCmd.Release();
}
catch (_com_error& e)
{
m_bConn = false;
DMPcomERR(e);
#ifdef _DEBUG
OutputDebugString(strSQL);
#endif
return false;
}
catch(...)
{
#ifdef _DEBUG
OutputDebugString(strSQL);
#endif
return false;
}
return true;
}
bool CMyDataBase::GetMTmsg(CMTMsg& Mtmsg)
{
Mtmsg.Reset();
if (!OpenDB())
return false;
CString strSQL;
try
{
_CommandPtr pCmd;
_RecordsetPtr pRs;
TESTHR(pCmd.CreateInstance(__uuidof(Command)));
TESTHR(pRs.CreateInstance(__uuidof(Recordset)));
strSQL.Format("%s", "select top 1 * from sms_send where status = 0 ");
pCmd->ActiveConnection = m_pConn;
pCmd->CommandText = _bstr_t(strSQL);
pCmd->CommandType = adCmdText;
pCmd->Parameters->Refresh();
pRs = pCmd->Execute(NULL, NULL, adCmdText);
if (!pRs->adoEOF)
{
Mtmsg.m_iId = atoi((LPTSTR)RSGetVALUE(L"Id"));
Mtmsg.m_strMobile = (LPTSTR)RSGetVALUE(L"Mobile");
Mtmsg.m_strContent = (LPTSTR)RSGetVALUE(L"content");
Mtmsg.m_strEId = (LPTSTR)RSGetVALUE(L"Eid");
pRs->MoveNext();
}
if (pRs->GetState() != adStateClosed)
pRs->Close();
pRs.Release();
pCmd.Release();
}
catch (_com_error& e)
{
m_bConn = false;
DMPcomERR(e);
#ifdef _DEBUG
OutputDebugString(strSQL);
#endif
return false;
}
catch(...)
{
//LOG();
#ifdef _DEBUG
OutputDebugString(strSQL);
#endif
return false;
}
return true;
}
bool CMyDataBase::SetMtmsgFlag(int iId, int iStatus)
{
CString strSQL;
strSQL.Format("update sms_send set status = %d where id = %d", iStatus, iId);
return ExecuteSQL( strSQL );
}
bool CMyDataBase::MoveMtmsgToBak(int iId)
{
CString strSQL;
strSQL.Format("insert into sms_Already_send select * from sms_send where id = %d", iId);
if(ExecuteSQL( strSQL ))
{
strSQL.Format("delete sms_send where id = %d", iId);
return ExecuteSQL( strSQL );
}
return false;
}
------
执行SQL参看:ExecuteSQL
取数据参考:GetMTmsg
#5
看起来好复杂啊!我是初学vc++ 所以看不太懂...~_~
#6
先学会调试,会调试比会一大堆概念重要多了。看看是不是你的m_pConnection的创建是不是有问题,此外,字符串应该以bstr的方式传入
#7
::CoInitialize(NULL);//初始化COM
HRESULT hr=m_pConnection.CreateInstance("ADODB.Connection");
if(SUCCEEDED(hr))
{
try
{
// 打开本地SQL库
//m_pConnection->Open("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Data.mdb;Jet OLEDB:Database Password=","","",adModeUnknown);(accesss数据库,Data.mdb与工程在同一目录下)
m_pConnection->Open("driver={SQL Server};Server=127.0.0.1;DATABASE=netmanage;UID=;PWD=","","",adModeUnknown);
return true;
}
catch(_com_error e)//COM错误取得,当执行COM功能的时候,如果出错,可以捕捉到_com_error的异常
{
CString strComError;
strComError.Format("错误编号: %08lx\n错误信息: %s\n错误源: %s\n错误描述: %s",
e.Error(), // 错误编号
e.ErrorMessage(), // 错误信息
(LPCSTR) e.Source(), // 错误源
(LPCSTR) e.Description()); // 错误描述
::MessageBox(NULL,strComError,"错误",MB_ICONEXCLAMATION);
return FALSE;
}
}
HRESULT hr=m_pConnection.CreateInstance("ADODB.Connection");
if(SUCCEEDED(hr))
{
try
{
// 打开本地SQL库
//m_pConnection->Open("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Data.mdb;Jet OLEDB:Database Password=","","",adModeUnknown);(accesss数据库,Data.mdb与工程在同一目录下)
m_pConnection->Open("driver={SQL Server};Server=127.0.0.1;DATABASE=netmanage;UID=;PWD=","","",adModeUnknown);
return true;
}
catch(_com_error e)//COM错误取得,当执行COM功能的时候,如果出错,可以捕捉到_com_error的异常
{
CString strComError;
strComError.Format("错误编号: %08lx\n错误信息: %s\n错误源: %s\n错误描述: %s",
e.Error(), // 错误编号
e.ErrorMessage(), // 错误信息
(LPCSTR) e.Source(), // 错误源
(LPCSTR) e.Description()); // 错误描述
::MessageBox(NULL,strComError,"错误",MB_ICONEXCLAMATION);
return FALSE;
}
}
#8
还要在STAAFX.H中导入:
#import "C:\Program Files\Common Files\System\ado\msado15.dll" no_namespace rename("EOF","adoEOF")
#import "C:\Program Files\Common Files\System\ado\msado15.dll" no_namespace rename("EOF","adoEOF")
#9
已经解决问题了 呵呵 谢谢各位了!!
#10
楼主我也是这个问题啊 ,你都解决了 ,能不能说下是怎么解决的啊 ??
#11
楼主亮亮解决方法啊 还有一大群我们这初学者也想知道 谢谢
#12
楼主 求解决方法
#13
很有可能是密码的问题,如果你的access数据库有密码,则在open函数中应该加入密码,如:
pConnection->Open("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=JyDB.mdb ;Jet OLEDB:Database Password=jy_agt&pwd ","","",adModeUnknown);
pConnection->Open("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=JyDB.mdb ;Jet OLEDB:Database Password=jy_agt&pwd ","","",adModeUnknown);