16,472
社区成员
发帖
与我相关
我的任务
分享
// 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;
}
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);