资源描述:
《c++控制台连接sql数据库.doc》由会员上传分享,免费在线阅读,更多相关内容在行业资料-天天文库。
1、例:创建数据库media其中有表tb_user列name、idnum一、连接数据库#import"C:ProgramFilesCommonFilesSystemadomsado15.dll"no_namespacerename("EOF","rsEOF")#pragmacomment(lib,"winmm.lib")_ConnectionPtrpConnection;_CommandPtrpCommand;_RecordsetPtrpRecordset;pRecordset.CreateInstance("ADODB.Recordset");pConnectio
2、n.CreateInstance("ADODB.Connection");pCommand.CreateInstance("ADODB.Command");1、打开数据库(其中用户名密码是安装数据库时设定的)_bstr_tstrConnect="Provider=SQLOLEDB;Server=(local);Database=media;uid=sa;pwd=2944028a;";pConnection->Open(strConnect,"","",adModeUnknown);注:如果要连接局域网内其他电脑上的数据库_bstr_tstrConnect="Provide
3、r=SQLOLEDB;DataSource=192.168.1.119;Database=media;uid=sa;pwd=2944028a;";pConnection->Open(strConnect,"","",adModeUnknown);1、打开表pRecordset->Open("SELECT*FROMtb_user",pConnection.GetInterfacePtr(),adOpenDynamic,adLockOptimistic,adCmdText);一、添加数据Charname[]=”hwm”;Charnum[]=”12345”;pRecordset
4、->AddNew();//添加行pRecordset->PutCollect("name",_variant_t(name));//写入数据pRecordset->PutCollect("num",_variant_t(num));pRecordset->Update();//更新数据库二、更改位置及判断pRecordset->MoveFirst();//移动到第一行pRecordset->MoveNext();//移动到下一行pRecordset->BOF//判断表是否为空pRecordset->rsEOF//判断表是否结束三、读取数据if(!pRecordset->B
5、OF)//判断表是否为空pRecordset->MoveFirst();else{cout<<"表内数据为空";return0;}_variant_tvname,vnum,Charname[30];Charnum[30];vname=pRecordset->GetCollect("name");vnum=pRecordset->GetCollect("num");strcpy(name,(LPCSTR)_bstr_t(vname));strcpy(num,(LPCSTR)_bstr_t(vnum));一、修改数据if(!pRecordset->BOF)//判断表是否为空p
6、Recordset->MoveFirst();else{cout<<"表内数据为空";return0;}pRecordset->MoveNext();//移动到想要修改的行pRecordset->PutCollect("name",_variant_t(name));pRecordset->PutCollect("num",_variant_t(num));二、删除数据if(!pRecordset->BOF)//判断表是否为空pRecordset->MoveFirst();else{cout<<"表内数据为空";return0;}pRecordset->MoveNext(
7、);//移动到想要删除的行pRecordset->Delete(adAffectCurrent);//删除pRecordset->Update();