您的位置:首页 > 编程语言 > C语言/C++

【C++_一点用法】VC访问Access数据库

2013-03-25 21:56 357 查看

开始写写博客,做做笔记,学习学习。

C++遇上Access,Mark一下!

#include "stdafx.h"
#include <stdio.h>
#import "c:\program files\common files\system\ado\msado15.dll" no_namespace rename("EOF", "adoEOF")

int main(int argc, char* argv[])
{
_ConnectionPtr m_pConnection;  //到access数据库的链接对象
_RecordsetPtr m_pRecordset;  //结果集对象
CoInitialize(NULL);  //初始化
m_pConnection.CreateInstance(__uuidof(Connection)); //实例化对象

//连到具体某个mdb
try
{
m_pConnection->Open("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Teacher.mdb", "", "", adModeUnknown);
}
catch(_com_error e)
{
printf("数据库连接失败!");
return 0;
}

m_pRecordset.CreateInstance(__uuidof(Recordset)); //实例化结果集对象
//执行sql语句
try
{
m_pRecordset->Open("select * from 教师信息", m_pConnection.GetInterfacePtr(), adOpenDynamic, adLockOptimistic, adCmdText);
}
catch(_com_error *e)
{
printf(e->ErrorMessage());
if(m_pConnection->State)
{
m_pConnection->Close();
m_pConnection= NULL;
}
return 0;
}

//处理结果集
try
{
//若结果为空,结束
if(m_pRecordset->BOF)
{
printf("表内数据为空!");
if(m_pConnection->State)
{
m_pRecordset->Close();
m_pRecordset = NULL;
m_pConnection->Close();
m_pConnection= NULL;
}
return 0;
}
//游标定位到第一条记录
m_pRecordset->MoveFirst();
_variant_t var; //从结果集中取出的数据放到var中
char *t1;
while(!m_pRecordset->adoEOF)
{
var= m_pRecordset->GetCollect("教师编号");
if(var.vt != VT_NULL) t1 = _com_util::ConvertBSTRToString((_bstr_t)var);

printf("%s  ", t1);

var= m_pRecordset->GetCollect("姓名");
if(var.vt != VT_NULL) t1 = _com_util::ConvertBSTRToString((_bstr_t)var);
else t1 = "NULL";
printf("%s  ", t1);

var= m_pRecordset->GetCollect("手机号码");
if(var.vt != VT_NULL) t1 = _com_util::ConvertBSTRToString((_bstr_t)var);
else t1 = "NULL";
printf("%s  ", t1);

var= m_pRecordset->GetCollect("家庭电话");
if(var.vt != VT_NULL) t1 = _com_util::ConvertBSTRToString((_bstr_t)var);
else t1 = "NULL";
printf("%s  ", t1);

var= m_pRecordset->GetCollect("办公电话");
if(var.vt != VT_NULL) t1 = _com_util::ConvertBSTRToString((_bstr_t)var);
else t1 = "NULL";
printf("%s  ", t1);

var= m_pRecordset->GetCollect("办公地址");
if(var.vt != VT_NULL) t1 = _com_util::ConvertBSTRToString((_bstr_t)var);
else t1 = "NULL";
printf("%s  ", t1);

var= m_pRecordset->GetCollect("办公邮编");
if(var.vt != VT_NULL) t1 = _com_util::ConvertBSTRToString((_bstr_t)var);
else t1 = "NULL";
printf("%s  ", t1);

var= m_pRecordset->GetCollect("E-Mail");
if(var.vt != VT_NULL) t1 = _com_util::ConvertBSTRToString((_bstr_t)var);
else t1 = "NULL";
printf("%s\n\n", t1);

m_pRecordset->MoveNext();
}
}
catch(_com_error *e)
{
printf(e->ErrorMessage());
}

//退出程序时的处理
if(m_pConnection->State)
{
m_pRecordset->Close();
m_pRecordset = NULL;
m_pConnection->Close();
m_pConnection= NULL;
}

system("pause");
return 0;
}


运行结果如下:



以前研究过怎么新建数据库,用的是ado的方式。

有许多大神都写过,我就不献丑了,贴上是链接
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  编程 C++ 一点用法