C++连接数据库一

#include <icrsint.h>
#include<iostream>
#include<iomanip>
#include <string>
#include <vector>
/*
连接sql server数据库
*/
using namespace std;
#import "c:\program files\common files\system\ado\msado15.dll"  no_namespace rename("EOF", "adoEOF")
void main()
{
CoInitialize(NULL);   //初始化com组件
_ConnectionPtr  sqlSp;
_RecordsetPtr m_pRecordset;
// vector<string> result;
HRESULT hr=sqlSp.CreateInstance(__uuidof(Connection));     //实例化Connection对象
if(FAILED(hr))          
{
cout<<"_ConnectionPtr对象指针实例化失败!!!"<<endl;
return ;
}
else {
try {
_bstr_t strConnect="Driver={sql server};server=127.0.0.1,1433;uid=sa;pwd=;database=Stu;";
sqlSp->Open(strConnect,"","",adModeUnknown);    //打开与数据库的连接
}
catch(_com_error &e) {
cout<<e.Description()<<endl;            
}

if(FAILED(m_pRecordset.CreateInstance( __uuidof( Recordset ))))     //实例化数据集
{
cout<<"记录集对象指针实例化失败!"<<endl;
return;
}
try {
// m_pRecordset->Open("select * from  Stu",(IDispatch*)sqlSp,adOpenDynamic,adLockOptimistic, adCmdText);
m_pRecordset=sqlSp->Execute("select * from Stu",NULL,adConnectUnspecified);   //取出结果
}
catch (_com_error &e)
{
cout << e.Description()<<endl;
// cout<<"没有结果集"<<endl;
}
try {
m_pRecordset->MoveFirst();
while(!m_pRecordset->adoEOF) 
{
// string stuNo=(char*)(_bstr_t)(m_pRecordset->Fields->GetItem(_variant_t("stuId"))->Value);
string stuNo=(_bstr_t)m_pRecordset->GetCollect("stuId");
string stuName=(_bstr_t)m_pRecordset->GetCollect("stuName");
string stuSex=(_bstr_t)m_pRecordset->GetCollect("stuSex");
string stuAge=(_bstr_t)m_pRecordset->GetCollect("stuAge");
string stuLocation=(_bstr_t)m_pRecordset->GetCollect("stuLocation");
string stuDept=(_bstr_t)m_pRecordset->GetCollect("stuDept");
/* result.push_back(stuNo);
result.push_back(stuName);
result.push_back(stuSex);
result.push_back(stuAge);
result.push_back(stuLocation);
result.push_back(stuDept);     */


cout<<stuNo<<"  "<<stuName<<"  "<<stuSex<<"   "<<stuAge<<"  "<<stuLocation
<<"  "<<stuDept<<endl;    


m_pRecordset->MoveNext();
}
}
catch (_com_error &e)
{
cout << e.Description()<<endl;
}
}
if(m_pRecordset!=NULL)
m_pRecordset->Close();
if(sqlSp!=NULL)
sqlSp->Close();
sqlSp->Release();
m_pRecordset->Release();
CoUninitialize();
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值