SQLFetch() 函数获取结果数据有三种方式:
1. 基于SQLBindCol 函数
2. 基于SQLGetData 函数
3. SQLBindCol 和 SQLGetData 函数结合。
基于SQLBindCol 函数的方法参见: Mysql使用SQLFetch()获取结果数据 - 基于 SQLBindCol
目录
4. SQLBindCol 函数参数详细说明,摘自MSDN。
1. 函数及参数简介
应用程序不使用SQLBindCol将结果集列绑定到程序变量。每次调用SQLFetch之后,应用程序都会为结果集中的每一列调用SQLGetData一次。SQLGetData指示驱动程序将数据从特定的结果集列转移到特定的程序变量,并指定列和变量的数据类型。这允许驱动程序在结果列和程序变量具有不同的数据类型时转换数据。Text、ntext和image列通常太大,无法放入程序变量,但仍然可以使用SQLGetData检索。如果结果列中的文本、ntext或图像数据大于程序变量,SQLGetData将返回SQL_SUCCESS_WITH_INFO和SQLSTATE 01004(右截短的字符串数据)。对SQLGetData的连续调用将返回连续的文本或图像数据块。
简单来说使用 SQLGetData 时,每调用一次 SQLFetch函数获取的结果集,就调用 SQLGetData 获取指定列的值。
SQLRETURN SQLGetData(
SQLHSTMT StatementHandle, // [Input]
SQLUSMALLINT ColumnNumber, // [Input]
SQLSMALLINT TargetType, // [Input]
SQLPOINTER TargetValuePtr, // [Output]
SQLLEN BufferLength, // [Input]
SQLLEN * StrLen_or_IndPtr // [Output]
);
简单的来说:
参数1:操作的句柄。
参数2:要进行操作的列号,从1开始
参数3:该列的数据类型
参数4:存储该列的结果值变量
参数5:指定结果数据的大小
参数6:返回获取的结果的大小
具体参数释义见文末,摘自MSDN。
2. 代码示例:
2.1 示例
SQLCHAR t1[32], t2[255], t3[255];
SQLLEN Strlen_or_IndPtr = 0;
for (int i = 0;; i++)
{
res = SQLFetch(myStatementHandle); //获取结果集
res = SQLGetData(myStatementHandle, 1, SQL_C_DEFAULT, &t1, 32, &Strlen_or_IndPtr); // 获取结果集中列数据
res = SQLGetData(myStatementHandle, 2, SQL_C_DEFAULT, &t2, 255, &Strlen_or_IndPtr);
res = SQLGetData(myStatementHandle, 3, SQL_C_DEFAULT, &t3, 255, &Strlen_or_IndPtr);
if (res == SQL_ERROR || res == SQL_SUCCESS_WITH_INFO)
break;
if (res == SQL_SUCCESS || res == SQL_SUCCESS_WITH_INFO)
{
cout << i + 1 << " -- " << t1 <<" -- " << t2 << " -- " << t3 << " -- " << Strlen_or_IndPtr << endl;
}
else
{
cout << res;
break;
}
}
【释】:
t1[32], t2[255], t3[255] 变量和数据表的列对应。如下图:
注意:定义变量的时候一定要指定变量类型,不然以SQLPOINTER 定义变量时,结果为ASCII码,见下面的结果图2。
res = SQLGetData(myStatementHandle, 1, SQL_C_DEFAULT, &t1, 32, &Strlen_or_IndPtr);
myStatementHandle:为句柄;
1:代表第 1 列;
SQL_C_DEFAULT:指定结果的数据类型,根据数据表中的定义来决定,其他C类型名称见文末;SQL_C_DEFAULT 是根据数据源类型来决定变量类型
t1:保存结果变量;
32:指定结果的大小,注意要留出终止字符的空间;
Strlen_or_IndPtr:返回结果数据的大小。
2.2 结果:
如果存储结果的指针定义成 SQLPOINTER 类型,则结果为ASCII值,见下图2。
3. 其他C类型名称
(不全,详情查看sqlext.h)
#define SQL_C_CHAR SQL_CHAR /* CHAR, VARCHAR, DECIMAL, NUMERIC */
#define SQL_C_LONG SQL_INTEGER /* INTEGER */
#define SQL_C_SHORT SQL_SMALLINT /* SMALLINT */
#define SQL_C_FLOAT SQL_REAL /* REAL */
#define SQL_C_DOUBLE SQL_DOUBLE /* FLOAT, DOUBLE */
4. SQLGetData 函数参数详细说明
摘自MSDN。
(1)StatementHandle
(2)ColumnNumber
(3)TargetType
(4)TargetValuePtr
(5)BufferLength
(6)StrLen_or_IndPtr
-
The length of the data available to return
-
SQL_NO_TOTAL
-
SQL_NULL_DATA