封装ADO

yuyunliuhen 2008-06-30 03:21:03
直接进行ADO操作时候,没遇到什么问题,但把他封装后,去使用 出现不少问题了 ,没提示错误,但没有执行SQl 我把代码贴一下, 有点乱,麻烦看一下,谢谢!

// stdafx.h : 标准系统包含文件的包含文件,
// 或是经常使用但不常更改的
// 特定于项目的包含文件
//

#pragma once

#include <stdio.h>
#include <tchar.h>



// TODO: 在此处引用程序需要的其他头文件
#import "C:\Program Files\Common Files\System\ado\msado15.dll" no_namespace rename("EOF","EndOfFile")



#pragma once
#include "stdafx.h"
class ExADO
{
public:
ExADO(void);
bool InitCom();//初始化COM
void Instance();//实例化指针对象
void PrintProviderError(_ConnectionPtr pConnection);// Print Provider Errors from Connection object.
void PrintComError(_com_error &e);// Print COM errors.
bool SetConnection();//连接数据库
_bstr_t GetState(int intState);//获取连接状态
bool Move(int numRec);//记录从开始移动numRec位
bool MoveNext();//移动到下一个位置
bool MoveFirst(); //移到第一个位置
bool MoveLast();//移到最后位置
bool MovePrevious();//移到前一个位置
bool Execute(_bstr_t sSQL);// 执行SQL操作
void PrintOutput(_RecordsetPtr pRstTemp);//打印输出

inline void TESTHR(HRESULT x) { if FAILED(x) _com_issue_error(x); };

~ExADO(void);

private:
_ConnectionPtr cnn;
_RecordsetPtr rst;
_CommandPtr cmd;
FieldsPtr pFldLoop ;
_variant_t vtIndex;



};



#include "ExADO.h"

ExADO::ExADO(void)
{
cnn=NULL;
rst=NULL;
cmd=NULL;
pFldLoop=NULL;
vtIndex.vt = VT_I2;
}

ExADO::~ExADO(void)
{
::CoUninitialize();
}
bool ExADO::InitCom()
{
if ( FAILED(::CoInitialize(NULL)) )
return false;
return true;
}
void ExADO::PrintComError(_com_error &e)
{
_bstr_t bstrSource(e.Source());
_bstr_t bstrDescription(e.Description());

// Print COM errors.
printf("Error\n");
printf("\tCode = %08lx\n", e.Error());
printf("\tCode meaning = %s\n", e.ErrorMessage());
printf("\tSource = %s\n", (LPCSTR) bstrSource);
printf("\tDescription = %s\n", (LPCSTR) bstrDescription);

}

void ExADO::PrintProviderError(_ConnectionPtr pConnection)
{
// Print Provider Errors from Connection object.
// pErr is a record object in the Connection's Error collection.
ErrorPtr pErr = NULL;

if ( (pConnection->Errors->Count) > 0) {
long nCount = pConnection->Errors->Count;
// Collection ranges from 0 to nCount -1.
for ( long i = 0 ; i < nCount ; i++ ) {
pErr = pConnection->Errors->GetItem(i);
printf("\t Error number: %x\t%s", pErr->Number, pErr->Description);
}
}

}

void ExADO::Instance()
{
try
{
TESTHR(cnn.CreateInstance(__uuidof(Connection)));
TESTHR(rst.CreateInstance(__uuidof(Recordset)));
TESTHR(cmd.CreateInstance(__uuidof(Command)));

}

catch (_com_error &e)
{
PrintComError(e);

}
}

bool ExADO::SetConnection()
{
try
{
/*

ADO 连接SQL数据库的两种方式:
cnn->Open("driver={SQL Server};Server=d996d36574f0499;DATABASE=test;UID=sa;PWD=sbivfh","","",adModeUnknown);
cnn->Open("Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False; \
Initial Catalog=test;Data Source=(local)","","",NULL);
*/
// Open a connection using OLE DB syntax.
// cnn->Open("driver={SQL Server};Server=sky;DATABASE=master;Integrated Security=SSPI;","","",adModeUnknown);
cnn->ConnectionString = "Provider='sqloledb.1';Data Source='(local)';Persist Security Info=False; "
"Initial Catalog='master';Integrated Security='SSPI';";
cnn->ConnectionTimeout = 3;
cnn->Open("", "", "",adConnectUnspecified);
//printf("cnn state: %s\n", (LPCTSTR)cnn->GetState());
printf("cnn state: %s\n", (LPCTSTR)GetState(cnn->State));


}
catch(_com_error &e)
{
// Notify user of any errors. Pass a connection pointer accessed from the Connection.
if (cnn)
{
PrintProviderError(cnn);
PrintComError(e);
return false;
}
}
if (cnn)
if (cnn->State == adStateOpen)
cnn->Close();
return true;
}

_bstr_t ExADO::GetState(int intState) {
_bstr_t strState;
switch(intState) {
case adStateClosed:
strState = "adStateClosed";
break;
case adStateOpen:
strState = "adStateOpen";
break;
default:
;
}
return strState;
}

bool ExADO::Move(int numRec)
{
try
{
rst->MoveFirst();
rst->Move(numRec);

}
catch(_com_error &e)
{
PrintComError(e);
return false;
}
return true;
}
bool ExADO::MoveFirst()
{
try
{
rst->MoveFirst();

}
catch(_com_error& e)
{
PrintComError(e);
return false;

}
return true;
}

bool ExADO::MoveLast()
{
try
{
rst->MoveLast();
}
catch(_com_error &e)
{
PrintComError(e);
return false;
}
return false;

}

bool ExADO::MovePrevious()
{
try
{
rst->MovePrevious();
}
catch(_com_error&e)
{
PrintComError(e);
return false;
}

return false;
}

bool ExADO::Execute(_bstr_t sSQL)
{
try
{
cmd->ActiveConnection = cnn;
//cmd->CommandText = sSQL;
// Open titles table, casting Connection pointer to an
// IDispatch type so converted to correct type of variant.

//rst->Open ("ACME__EMPLOYEES", _variant_t((IDispatch *) cnn, true), \
//adOpenStatic, adLockOptimistic, adCmdTable);
//PrintOutput(rst);

rst->Open (sSQL, _variant_t((IDispatch *)cnn, true),adOpenStatic, adLockOptimistic, adCmdTable);


// Enumerate the Fields collection of the Employees table.
pFldLoop = rst->GetFields();
for (int intFields = 0 ; intFields < (int)pFldLoop->GetCount() ; intFields++)
{
vtIndex.iVal = intFields;

// Because Value is the default property of a Field object,the use of
// the actual keyword here is optional.
printf(" %s = %s\n\n" ,
(LPCSTR) pFldLoop->GetItem(vtIndex)->GetName(),
(LPCSTR) (_bstr_t) pFldLoop->GetItem(vtIndex)->Value);

}


}
catch(_com_error &e)
{
// Notify the user of errors if any.
// Pass a connection pointer accessed from the Recordset.
_variant_t vtConnect = rst->GetActiveConnection();

// GetActiveConnection returns connect string if connection
// is not open, else returns Connection object.
switch(vtConnect.vt)
{
case VT_BSTR:
PrintComError(e);
break;
case VT_DISPATCH:
PrintProviderError(vtConnect);
break;
default:
printf("Errors occured.");
break;
}
return false;
}
return true;

}


void ExADO::PrintOutput(_RecordsetPtr pRstTemp) {
// Ensure at top of recordset.
pRstTemp->MoveFirst();

// If EOF is true, then no data and skip print loop.
if ( pRstTemp->EndOfFile )
printf("\tRecordset empty\n");
else {
// Define strings for output conversions. Initialize to first record's values.
_bstr_t temp1;
_bstr_t trmp2;

// Enumerate Recordset and print from each.
while ( !(pRstTemp->EndOfFile) )
{
// Convert variant string to convertable string type.
//bstrTitle = pRstTemp->Fields->GetItem("filed1")->Value;
//bstrType = pRstTemp->Fields->GetItem("file2d")->Value;
//printf("\t%s, %s \n", (LPCSTR) filed1, (LPCSTR) filed2);

pRstTemp->MoveNext();
}
}
}



测试程序

#include<stdio.h>
#include "ExADO.h"
int main()
{
_bstr_t strSQL("UPDATE Titles SET PHONE = '12345567' WHERE PHONE = 'CJBQ39HKQH");
ExADO adotest;
adotest.InitCom();
adotest.Instance();
adotest.SetConnection();
adotest.Execute(strSQL);
return 0;
}
...全文
151 17 打赏 收藏 转发到动态 举报
写回复
用AI写文章
17 条回复
切换为时间正序
请发表友善的回复…
发表回复
googlg 2011-04-01
  • 打赏
  • 举报
回复
lz 的封装挺好 学习了
yuyunliuhen 2008-07-01
  • 打赏
  • 举报
回复
恩 谢谢各位,也参看过很多现成的东西,估计是数据库系统的问题,我想还是重做系统,重装软件吧,虽然时间会耗上一点 ^_^
明湖居士2018 2008-07-01
  • 打赏
  • 举报
回复
网上有一个ado.h和ado.cpp,里面有很多已经封装好的ado类,可以试试那个
yuyunliuhen 2008-07-01
  • 打赏
  • 举报
回复
up .
yuyunliuhen 2008-07-01
  • 打赏
  • 举报
回复
[Quote=引用 9 楼 Mackz 的回复:]
你用的是不是桌面版的数据库引擎MSDE?MSDE默认安装是不安装网络服务的,看一下安装说明。
[/Quote]

SQL2008,在网上查了些资料,TELNET (服务器名)1433,1433没有打开,去配置服务网络,打开TCP/IP 命名管道协议,关闭SQLSERVER服务,然后就重启不了了,我想可能修复可以解决,然后提示这样的错误,
安装程序遇到如下错误:
misGetProductinfo 无法检索Product code 为“{CEF8540-CF57-485B-9994-BE9E02D29193}"的包的ProductVersion.错误代码1605;

没法,我把他给卸载,清理系统 ,直接就安装不上了,错误提示还是上面的。不知道哪位遇到这样的情况没,有好的解决方法也来分享下 Thank you!
scq2099yt 2008-06-30
  • 打赏
  • 举报
回复
如果没执行sql那说明是其他的问题。
如果执行了就try catch看是什么错误
haolaile 2008-06-30
  • 打赏
  • 举报
回复
楼主用什么?
haolaile 2008-06-30
  • 打赏
  • 举报
回复
我用SQL 2008的啊
菜牛 2008-06-30
  • 打赏
  • 举报
回复
你用的是不是桌面版的数据库引擎MSDE?MSDE默认安装是不安装网络服务的,看一下安装说明。
haolaile 2008-06-30
  • 打赏
  • 举报
回复
设置断点,一步一步跟下
yuyunliuhen 2008-06-30
  • 打赏
  • 举报
回复
找到错误了,正在看资料,看能否解决,^_^ 谢谢上面几位
Source = Microsoft OLE DB Provider for SQL Server
Description = [DBNETLIB][ConnectionOpen (Connect()).]SQL Server 不存在或
拒绝访问。

这个好像是与端口1433有关 netstat -an 没有查到这个端口是开的 但进程中可查到这个SQLSERVR进程 ,
sanshao27 2008-06-30
  • 打赏
  • 举报
回复
如果没错误提示,你既然知道没执行没有执行SQl,就在这个操作之前进行断点跟踪一下。
jameshooo 2008-06-30
  • 打赏
  • 举报
回复
试试这个:
CComQIPtr<IDispatch> disp = cnn;
rst->Open (sSQL, disp, adOpenStatic, adLockOptimistic, adCmdTable);
闪破风浪 2008-06-30
  • 打赏
  • 举报
回复
断点追踪一下
superhard_d 2008-06-30
  • 打赏
  • 举报
回复
建议楼主调试一下,看看参数什么的对不对
yuyunliuhen 2008-06-30
  • 打赏
  • 举报
回复
出错可能存在的地方,以前也这样写的,不知道有没有问题哈

cnn->ConnectionString = "Provider='sqloledb.1';Data Source='(local)';Persist Security Info=False; "
"Initial Catalog='master';Integrated Security='SSPI';";
cnn->ConnectionTimeout = 3;
cnn->Open("", "", "",adConnectUnspecified);


cmd->ActiveConnection = cnn;
rst->Open (sSQL, _variant_t((IDispatch *)cnn, true),adOpenStatic, adLockOptimistic, adCmdTable);

yuyunliuhen 2008-06-30
  • 打赏
  • 举报
回复
文件分别是 stdafx.h ExADO.h ExADO.cpp test.cpp

16,472

社区成员

发帖
与我相关
我的任务
社区描述
VC/MFC相关问题讨论
社区管理员
  • 基础类社区
  • Web++
  • encoderlee
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

        VC/MFC社区版块或许是CSDN最“古老”的版块了,记忆之中,与CSDN的年龄几乎差不多。随着时间的推移,MFC技术渐渐的偏离了开发主流,若干年之后的今天,当我们面对着微软的这个经典之笔,内心充满着敬意,那些曾经的记忆,可以说代表着二十年前曾经的辉煌……
        向经典致敬,或许是老一代程序员内心里面难以释怀的感受。互联网大行其道的今天,我们期待着MFC技术能够恢复其曾经的辉煌,或许这个期待会永远成为一种“梦想”,或许一切皆有可能……
        我们希望这个版块可以很好的适配Web时代,期待更好的互联网技术能够使得MFC技术框架得以重现活力,……

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