VC++中的ADO宏的详细解说
VC++中的ADO宏的详细解说
VC++中的ADO宏
在VC++中一般使用ADO(Active Database Object) 进行数据库编程,由于函数调用中需要设置很多参数,不如VB中使用简单。实际编程中大部分参数实际都设置为一样的,处理方法也一样。笔者就将ADO对象(Connection、Recordset、Command)等的常见用法封装为宏(xOpenRecordset、xConnect、xDisconnect、xExecute、xCmdExecute)。只需在stdafx.h中加入如下文件,就可以大大减少编程工作量。
//文件名:db.h
//ADO数据库宏
//日期:08-10-2003
#if !defined(_DB_H)
#define _DB_H
#include "icrsint.h"
//根据实际路径修改
#import "C:/Program Files/Common Files/System/ado/msado15.dll" no_namespace rename("EOF","EndOfFile")
//数据库连接参数结构
struct Database
{
CString strUserName; //User's ID
CString strPassword; //User's password
CString strServer; //Name of database server
CString strDBName; //Name of database
};
typedef Database *pDatabase;
//打开记录集
#define xOpenRecordset(/*_RecordsetPtr*/ rs, /*_ConnectionPtr*/ cn,/*_bstr_t*/ bt) /
HRESULT hr_rs=S_OK;/
hr_rs=rs.CreateInstance(__uuidof(Recordset));/
ASSERT(SUCCEEDED(hr_rs));/
hr_rs=rs->Open(bt,cn.GetInterfacePtr(),adOpenDynamic,adLockOptimistic,adCmdText);/
ASSERT(SUCCEEDED(hr_rs));
//执行SQL语句
#define xExecute(/*_ConnectionPtr*/ cn,/*_bstr_t*/ bt) /
cn->Execute(bt,NULL,adExecuteNoRecords);
//连接数据库
//如果为非SQL Server数据库,请自行修改连接字符串
#define xConnect(/*_ConnectionPtr*/ cn, /*Database*/ database) /
_bstr_t bt_cn;/
HRESULT hr_cn=S_OK;/
bt_cn=(_bstr_t)"Provider=SQLOLEDB.1;Persist Security Info=False;User ID="+(_bstr_t)database.strUserName+(_bstr_t)";Password="+(_bstr_t)database.strPassword+(_bstr_t)";Initial Catalog="+(_bstr_t)database.strDBName+(_bstr_t)";Data Source="+(_bstr_t)database.strServer;/
CoInitialize(NULL); /
hr_cn=cn.CreateInstance(__uuidof(Connection));/
ASSERT(SUCCEEDED(hr_cn));/
hr_cn=cn->Open (bt_cn,_bstr_t(""),_bstr_t(""),adModeUnknown);/
ASSERT(SUCCEEDED(hr_cn));
//断开数据库
#define xDisconnect(/*_ConnectionPtr*/ cn) /
cn->Close ();/
CoUninitialize();
//执行Command命令
#define xCmdExecute(/*_CommandPtr*/ cmd,/*_RecordsetPtr*/ rs,/*_ConnectionPtr*/ cn,/*_bstr_t*/ bt) /
HRESULT hr_cmd=S_OK;/
hr_cmd=cmd.CreateInstance(__uuidof(Command));/
ASSERT(SUCCEEDED(hr_cmd));/
hr_cmd=rs.CreateInstance(__uuidof(Recordset));/
ASSERT(SUCCEEDED(hr_cmd));/
cmd->CommandText =bt;/
cmd->CommandType = adCmdText;/
cmd->ActiveConnection =cn;/
rs=cmd->Execute (NULL,NULL,adCmdText );
//end of file
#endif