我正在编写使用 SQL Server 本机客户端 sqlncli.h 的小型 C++ 控制台应用程序(VS 2013 / Windows7)。我在程序中遇到了 NULL 字段的问题 - 我没有看到正确的值。
#include <windows.h>
#include <sql.h>
#include <sqlext.h>
#include <sqltypes.h>
#include <sqlncli.h>
#include <cstdio>
#include <string>
#include <iostream>
using namespace std;
int main()
{
SQLHENV environHandle;
SQLHDBC connectHandle;
SQLHSTMT statement;
SQLWCHAR* connectString = (SQLWCHAR*)TEXT("Driver={SQL Server};Server=XX.XX.XX.XX;Database=DBNAME;Trusted_Connection=yes;");
SQLRETURN status;
status = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &environHandle);
cout << "SQLAllocHandle returned " << status << "\r\n";
if (status == SQL_SUCCESS_WITH_INFO || status == SQL_SUCCESS)
{
status = SQLSetEnvAttr(environHandle, SQL_ATTR_ODBC_VERSION, (SQLPOINTER)SQL_OV_ODBC3_80, SQL_IS_INTEGER);
cout << "SQLSetEnvAttr returned " << status << "\r\n";
if (status == SQL_SUCCESS_WITH_INFO || status == SQL_SUCCESS)
{
status = SQLAllocHandle(SQL_HANDLE_DBC, environHandle, &connectHandle);
cout << "SQLAllocHandle SQL_HANDLE_DBC returned " << status << "\r\n";
if (status == SQL_SUCCESS_WITH_INFO || status == SQL_SUCCESS)
{
status = SQLDriverConnect(connectHandle, NULL, connectString, SQL_NTS, NULL, 256, NULL, SQL_DRIVER_NOPROMPT);
cout << "SQLDriverConnect returned " << status << "\r\n";
if (status == SQL_SUCCESS_WITH_INFO || status == SQL_SUCCESS)
{
status = SQLAllocHandle(SQL_HANDLE_STMT, connectHandle, &statement);
cout << "SQLAllocHandle SQL_HANDLE_STMT returned " << status << "\r\n";
if (status == SQL_SUCCESS_WITH_INFO || status == SQL_SUCCESS)
{
status = SQLExecDirect(statement, (SQLWCHAR*)TEXT("SELECT * FROM [DBNAME].[dbo].[Table1]"), SQL_NTS);
cout << "SQLExecDirect returned " << status << "\r\n";
if (status == SQL_SUCCESS_WITH_INFO || status == SQL_SUCCESS)
{
int rec_id;
int id;
char date[64];
char ps[201];
while (SQLFetch(statement) == SQL_SUCCESS)
{
SQLGetData(statement, 1, SQL_C_ULONG, &rec_id, 0, NULL);
SQLGetData(statement, 2, SQL_C_ULONG, &id, 0, NULL);
SQLGetData(statement, 3, SQL_C_CHAR, date, 64, NULL);
SQLGetData(statement, 4, SQL_C_CHAR, ps, 201, NULL);
cout << rec_id << " " << id << " " << date << " " << ps << endl;
}
}
}
cout << "Connected;";
cin.get();
}
}
}
}
return 0;
}
表1结构:
CREATE TABLE [dbo].[Table1](
[rec_id] [int] IDENTITY(1,1) NOT NULL,
[id] [int] NOT NULL,
[date] [datetime] NOT NULL,
[ps] [varchar](200) NULL
) ON [PRIMARY]
在控制台中,我看到前 3 个字段正确,但第四个字段就像╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠ 如何捕获 VARCHAR、NVARCHAR、FLOAT 类型的 NULL 字段?