VC++ 连接不上数据库,未指定类型的错误

rinima00 2011-05-28 09:30:06

void ADODB::OnInitADOConn()
{
::CoInitialize(NULL);
try
{
m_pConnection.CreateInstance("ADODB.Connection");
_bstr_t strConnect=
"Provider=SQLOLEDB.1;Persist Security Info=true;User ID=sa;Password=passwd;Initial Catalog=master;Data Source=localhost";

//oracle "Provider=MSDAORA.1;Persist Security Info=True;User ID=sys;Password=rinima88;Data Source=orcl";
m_pConnection->Open(strConnect,"","",adModeUnknown);
AfxMessageBox("连接成功");
}
catch(_com_error e)
{
CString errormessage;
errormessage.Format("连接数据库失败!\r\n 错误信息:%s",e.ErrorMessage());
AfxMessageBox(errormessage);
}
}
这个代码怎么连不上呢?
初学者 ,谢谢
...全文
363 4 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
King_hhuang 2011-06-07
  • 打赏
  • 举报
回复
ADO访问数据库的基本步骤:

(1)、引入ADO类 ,加到stdafx.h中#endif // _AFX_NO_AFXCMN_SUPPORT后面

#import "c:\program files\common files\system\ado\msado15.dll" \
no_namespace \
rename ("EOF", "adoEOF")

(2)、初始化COM (放在对话框初始化函数里面或者CXXXApp::InitInstance()中)

在MFC中可以用AfxOleInit();非MFC环境中用:
CoInitialize(NULL);

(3)、包含后就可以用3个智能指针了:_ConnectionPtr、_RecordsetPtr和_CommandPtr

(4)、连接数据库
HRESULT hr;
try
{
hr = m_pConnection.CreateInstance("ADODB.Connection");///创建Connection对象
if(SUCCEEDED(hr))
{
m_pConnection->ConnectionTimeout = 0;
hr = m_pConnection->Open( "Provider=SQLOLEDB.1;Password=密码;Persist Security Info=True;User ID=用户名;Initial Catalog=数据库名;Data Source=127.0.0.1(本机)", "", "", adConnectUnspecified);

m_pCommand.CreateInstance(__uuidof(Command));
m_pCommand->CommandTimeout = 5;
m_pCommand->ActiveConnection = m_pConnection;
}
}
catch(_com_error e)///捕捉异常
{
CString errormessage;
errormessage.Format("连接数据库失败!\r\n错误信息:%s,%s",e.ErrorMessage(),e.Description());
AfxMessageBox(errormessage);///显示错误信息
}

(5)、打开记录集
首先创建一个_RecordsetPtr实例,然后调用Open()得到一条SQL语句的执行结果
_RecordsetPtr m_pRecordset;
m_pRecordset.CreateInstance(__uuidof(Recordset));

// 在ADO操作中建议语句中要常用try...catch()来捕获错误信息,
// 因为它有时会经常出现一些意想不到的错误
try
{
m_pRecordset->Open("SELECT * FROM DemoTable",// 查询DemoTable表中所有字段
m_pConnection.GetInterfacePtr(), // 获取库接库的IDispatch指针
adOpenDynamic,
adLockOptimistic,
adCmdText);
}
catch(_com_error *e)
{
AfxMessageBox(e->ErrorMessage());
}

……

照着检查一下,看看你是不是每一步都做了,记得数据库操作try catch一下,捕捉一下有意义的错误提示
shiter 2011-06-07
  • 打赏
  • 举报
回复
估计是连接字符串的问题
"Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=student;Data Source=(local)"
这是我的连接本机的
注意:Data Source=(local)"
Oliver2891 2011-05-29
  • 打赏
  • 举报
回复
看看是啥错误呢?

4,018

社区成员

发帖
与我相关
我的任务
社区描述
VC/MFC 数据库
社区管理员
  • 数据库
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧