数据表结果如下:
Create Table TDEPARTMENT
(
DepartmentCode VARCHAR(20) NOT NULL,
DepartmentName VARCHAR(100) NOT NULL,
DepartmentAddress VARCHAR(200) NOT NULL
)
在Department.h中加入下列语句:
#import "c:/program files/common files/system/ado/msado15.dll" no_namespace rename("EOF","adoEOF")
程序按如下几步实现:
第一步,初始化COM对象,执行下列语句:
CoInitialize(NULL);
第二步,创建数据库连接对象,建立连接
_ConnectionPtr m_pConnection;
HRESULT hr;
try
{
hr = m_pConnection.CreateInstance("ADODB.Connection");
if(SUCCEEDED(hr))
{
m_pConnection->Open("Provider=SQLOLEDB.1;Persist Security Info=True;Initial Catalog=TopSales;data source=127.0.0.1","sa","sa",adModeUnknown);
}
}
catch(_com_error e)///捕捉异常
{
// 此处写异常处理程序
}
第三步,创建命令对象,赋予数据库脚本及参数,调用命令对象的Execute方法执行脚本。
_CommandPtr m_pCommand;
hr = m_pCommand.CreateInstance("ADODB.Command");
if (SUCCEEDED(hr))
{
_variant_t vNULL;
vNULL.vt = VT_ERROR;
vNULL.scode = DISP_E_PARAMNOTFOUND;///定义为无参数
m_pCommand->CommandText = "INSERT INTO TDEPARTMENT(DepartmentCode,DepartmentName,DepartmentAddress) VALUES('0001','公司','上海')";
m_pCommand->CommandType = adCmdText;
m_pCommand->ActiveConnection = m_pConnection;
m_pCommand->Execute(&vNULL,&vNULL,adCmdText);///执行命令,取得记录集
}
第四步,释放数据库连接
m_pConnection->Close();