开发者

How to read NULL value in ADO

I have a question related with NULL values I am connecting to SQL Server 2008 via ADO following the code:

#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;
}

the column I am reading att0 is like:

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

After executing the program I get:

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

I would like that when it detects a NULL value the program displays

    477
    113
    466
    527
    -1
    -1
    -1

Any idea, how to accomplish this?

All this works really great, but if in my table (which allows NULLS) I get an error when reading NUll

the ma开发者_运维问答in problem is in the section:

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

            );
            spRs->MoveNext();
        }
  • One more question, Why does the program have error in reading a NULL?


I'm sure there is some way to check for null values against the Recordset object but I don't know how that should be done in c++. But I do know how to fix this in the query instead.

Change your query to:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜