如何在ADO中读取NULL值

时间:2011-07-16 04:01:08

标签: c++ sql-server-2008 error-handling null

我有一个与NULL values相关的问题我在the code之后通过ADO连接到SQL Server 2008:

#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),我在阅读NUll时会出错

主要问题在以下部分:

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

            );
            spRs->MoveNext();
        }
  • 还有一个问题,为什么程序在读取NULL时出错?

1 个答案:

答案 0 :(得分:1)

我确信有一些方法可以检查Recordset对象的空值,但我不知道应该如何在c ++中完成。但我确实知道如何在查询中解决这个问题。

将您的查询更改为:

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