VS利用ADO连接数据库的操作
扫描二维码
随时随地手机看文章
(1)初始化COM库,引入ADO库定义文件
(2)用Connection对象连接数据库
(3)利用建立好的连接,通过Connection、Command对象执行SQL命令,或利用Recordset对象取得结果记录集进行查询、处理。
(4)使用完毕后关闭连接释放对象。
#include#include#include#import "C:msado15.dll" no_namespace rename("EOF","adoEOF") rename("BOF","adoBOF") using namespace std; int main(void) { CoInitialize(NULL); _ConnectionPtr pCon(__uuidof(Connection)); _RecordsetPtr pRSet(__uuidof(Connection)); try { pCon.CreateInstance("__uuidof(Connection)"); } catch(_com_error e) { cout<<"创建连接实例失败!"<<endl; cout<<e.Description()<<endl; cout<<e.HelpFile()<Open("driver={SQL Server};Server=.;DATABASE=linping;","sa","",adModeUnknown); } catch(_com_error e) { cout<<"数据库初始化失败!"<<endl; cout<<e.Description()<<endl; cout<<e.HelpFile()<<endl; return 0; } cout<<"连接成功!"<Execute("select * from card",NULL,adCmdText); if(!pRSet->adoBOF) { pRSet->MoveFirst(); } else { cout<<"表内数据为空!"<<endl; return 0; } vectorcolumn_name; for(int i = 0;iFields->GetCount();i++) { cout<Fields->GetItem(_variant_t((long)i))->Name<Fields->GetItem(_variant_t((long)i))->Name); } while(!pRSet->adoEOF) { vector::iterator iter = column_name.begin(); for(iter;iter!=column_name.end();iter++) { if(pRSet->GetCollect(*iter).vt !=VT_NULL) { cout<GetCollect(*iter)<<endl; } else { cout<<"NULL"<MoveNext(); cout<<endl; } } catch(_com_error &e) { cout<<e.Description()<<endl; cout<<e.HelpFile()<Close(); pCon->Close(); pRSet.Release(); pCon.Release(); } catch(_com_error &e) { cout<<e.Description()<<endl; cout<<e.HelpFile()<<endl; return 0; } CoUninitialize(); return 0; }