如何在ADO中读取NULL值

How to read NULL value in ADO

本文关键字:读取 NULL ADO      更新时间:2023-10-16

我有一个与NULL values相关的问题,我通过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 programaArchivos comunesSystemadomsado15.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 failedn");
        hr= spRs->Open( sSQL, sConn, adOpenForwardOnly, adLockReadOnly, adCmdText );
        if FAILED(hr) printf("Open failedn");
        while( !(spRs->adoEOF) ) {
            printf("%sn",
                    (char*) RsItem( spRs, 0L )
            );
            spRs->MoveNext();
        }
        spRs->Close();
    } catch( _com_error &e) {
        printf("Error:%sn",(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("%sn",
                    (char*) RsItem( spRs, 0L )
            );
            spRs->MoveNext();
        }
  • 还有一个问题,为什么程序在读取NULL时有错误?

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

将查询改为:

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