【求助】用VC6编程实现数据访问读写问题
首先,我是在用VC6来做SQL数据库的连接,所建工程均为控制台工程,用到了ADO数据访问,对于数据库中操作的表是“weather”,如下:
程序如下:
程序代码:
#include "iostream.h" #include "stdio.h" #include "afx.h" #include "icrsint.h" #import "C:\Program Files\Common Files\System\ado\msado15.dll" \ no_namespace rename("EOF", "adoEOF") void TESTHR(HRESULT x) {if FAILED(x) _com_issue_error(x);} void PrintError(const char *cs) {FILE *fd; fd=fopen("log\\ADOError.log","ab+"); fprintf(fd,"%s%c%c",cs,13,10); fclose(fd); } VOID PrintProviderError(_ConnectionPtr pConnection) { ErrorPtr pErr = NULL; long nCount = 0; long i = 0; if( (pConnection->Errors->Count) > 0) { nCount = pConnection->Errors->Count; for(i = 0; i < nCount; i++) { pErr = pConnection->Errors->GetItem(i); PrintError((LPCSTR)pErr->Description); } } } void AddNewX(void) { // Define ADO object pointers. // Initialize pointers on define. _RecordsetPtr pRecords = NULL; _ConnectionPtr pConnection = NULL; //Define Other variables IADORecordBinding *picRs = NULL; //Interface Pointer declared. //CEmployeeRs emprs; //C++ class object HRESULT hr = S_OK; _bstr_t strCnn("Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=weather_normal;"); try { //Open a connection strCnn=("Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=weather_normal;"); TESTHR(pConnection.CreateInstance(__uuidof(Connection))); hr = pConnection->Open(strCnn,"","",NULL); //_RecordsetPtr pRecords; TESTHR(pRecords.CreateInstance(__uuidof(Recordset))); hr=pRecords->Open("select weather,feel,temperature,wind,result from tab_weather ", _variant_t((IDispatch *) pConnection, true),adOpenKeyset,adLockOptimistic,adCmdText); TESTHR(hr); _bstr_t sql; _variant_t vweather; //变量声明 CString strusername; sql="select weather,feel,temperature,wind,result from tab_weather"; pRecords=pConnection->Execute(sql,NULL,adCmdText); while(!pRecords->adoEOF) { vweather = pRecords->GetCollect("weather");///取得weather字段的值 strusername = (TCHAR*)(_bstr_t)vweather ;//转换为字符串 printf("%s\n",strusername); pRecords->MoveNext();///移到下一条记录 } if (picRs) picRs->Release(); pRecords->Close(); pConnection->Close(); } catch(_com_error &e) { // Notify the user of errors if any. _variant_t vtConnect = pRecords->GetActiveConnection(); } } //========================================== //========================================== //========================================== void main() { if(FAILED(::CoInitialize(NULL))) return; AddNewX(); ::CoUninitialize(); }
运行结果如下:
我想达到的目的也就是通过程序访问到数据库表,将表中内容一个个显示出来,一行行显示出来,或者一列列显示出来。我程序已经完成了数据库的连接,只是在显示的时候有些疑问,我用到的是getcollect来读取字符串,现在我想用getrows来完成对表中内容的显示,自己一时间解决不了,希望把问题写出来,请教一下论坛里面的高手达人,帮助我解决,在此谢谢大家~