2011-07-16 70 views
1

讀取NULL值我有以下the codeNULL values我通過ADO連接到SQL Server 2008相關的一個問題:如何在ADO

#include "stdafx.h" 
#include <stdio.h> 

#include <windows.h> 
#include <ole2.h> 
#include <oleauto.h> 

#ifdef _MSC_VER 
#import "c:\Archivos de programa\Archivos comunes\System\ado\msado15.dll" rename ("EOF","adoEOF") no_namespace 
#else 

#define V_INT(X)   V_UNION(X, intVal) 
#define V_UINT(X)  V_UNION(X, uintVal) 
#include "msado15.tlh" 
#endif 

#include <comutil.h> 

struct InitOle 
{ 
    InitOle() { ::CoInitialize(NULL); } 
    ~InitOle() { ::CoUninitialize(); } 
} InitOle_tag; 

//------------------ utility fns to simplify access to recordset fields 
_bstr_t RsItem(_RecordsetPtr p, BSTR fldName) 
{ // by field name 
    return(p->Fields->Item[_variant_t(fldName)]->Value); 
} 
_bstr_t RsItem(_RecordsetPtr p, long nIdx) 
{ // by field # (0 is first) 
    return(p->Fields->Item[_variant_t(nIdx)]->Value); 
} 
//-------------------------------- The Program ---------------- 
int main() 
{ 
    _RecordsetPtr spRs; 
    HRESULT hr; 
    _bstr_t sConn= "driver={sql server};SERVER=VIRTUALPC;Database=test;UID=sa; PWD="; 
    _bstr_t sSQL= "SELECT att0 FROM [dbo].[mytable]"; 

    try 
    { 
     hr= spRs.CreateInstance(__uuidof(Recordset)); 
     if FAILED(hr) printf("CreateInstance failed\n"); 

     hr= spRs->Open(sSQL, sConn, adOpenForwardOnly, adLockReadOnly, adCmdText); 
     if FAILED(hr) printf("Open failed\n"); 

     while(!(spRs->adoEOF)) { 
      printf("%s\n", 
        (char*) RsItem(spRs, 0L) 

      ); 
      spRs->MoveNext(); 
     } 
     spRs->Close(); 
    } catch(_com_error &e) { 
     printf("Error:%s\n",(char*)e.Description()); 
    } 
    return 0; 
} 

我讀att0列是這樣的:

att0 
---- 
477 
113 
466 
527 
NULL 
NULL 
NULL 

執行程序後,我得到:

477 
113 
466 
527 
Error:(null) 
Press any key to continue . . . 

我當它檢測到NULL值時,程序顯示

477 
    113 
    466 
    527 
    -1 
    -1 
    -1 

任何想法,如何做到這一點?

這一切真正偉大的作品,但如果我的表(它允許NULLS)讀取空

,當我得到一個錯誤的主要問題是在部分:

while(!(spRs->adoEOF)) { 
      printf("%s\n", 
        (char*) RsItem(spRs, 0L) 

      ); 
      spRs->MoveNext(); 
     } 
  • 還有一問題,爲什麼程序在讀NULL時出錯?

回答

1

我敢肯定,有一些方法來檢查Recordset對象的空值,但我不知道應該如何在C++中完成。但我知道如何解決這個問題。

查詢更改爲:

SELECT coalesce(att0, -1) as att0 FROM [dbo].[mytable] 
+0

和假設我已經選擇表中的所有項目,有(*),是有可能做到像'SELECT COALESCE(*,-1)[DBO ]。[mytable]' – cMinor

+0

@cMinor - 不可能。順便說一句,你應該儘量避免使用*。 –

+0

好吧,所以我必須做at'0 coalesce(att0,-1),coalesce(att1,-1)ast1,coalesce(att2,-1)att2,coalesce(att3,-1)ast3,coalesce (att4,-1)ast4,...,' – cMinor