Postgresql 中文操作指南

36.7. Using Descriptor Areas #

SQL 描述符区域是一种处理 SELECTFETCHDESCRIBE 语句结果的更高级的方法。SQL 描述符区域将一行数据的数据连同元数据项分组为一个数据结构中。在执行动态 SQL 语句时元数据特别有用,因为结果列的性质可能无法提前得知。PostgreSQL 提供了两种使用描述符区域的方式:命名的 SQL 描述符区域和 C 结构 SQLDA。

An SQL descriptor area is a more sophisticated method for processing the result of a SELECT, FETCH or a DESCRIBE statement. An SQL descriptor area groups the data of one row of data together with metadata items into one data structure. The metadata is particularly useful when executing dynamic SQL statements, where the nature of the result columns might not be known ahead of time. PostgreSQL provides two ways to use Descriptor Areas: the named SQL Descriptor Areas and the C-structure SQLDAs.

36.7.1. Named SQL Descriptor Areas #

命名的 SQL 描述符区域由一个包含整个描述符相关信息的页眉和一个或多个项目描述符区域组成,其中每个项目描述符区域基本上描述结果行中的一列。

A named SQL descriptor area consists of a header, which contains information concerning the entire descriptor, and one or more item descriptor areas, which basically each describe one column in the result row.

在使用 SQL 描述符区域之前,您需要分配一个:

Before you can use an SQL descriptor area, you need to allocate one:

EXEC SQL ALLOCATE DESCRIPTOR identifier;

标识符充当描述符区域的“变量名”。当您不再需要描述符时,您应该取消分配它:

The identifier serves as the “variable name” of the descriptor area. When you don’t need the descriptor anymore, you should deallocate it:

EXEC SQL DEALLOCATE DESCRIPTOR identifier;

要使用描述符区域,请将其指定为 INTO 子句中的存储目标,而不是列出宿主变量:

To use a descriptor area, specify it as the storage target in an INTO clause, instead of listing host variables:

EXEC SQL FETCH NEXT FROM mycursor INTO SQL DESCRIPTOR mydesc;

如果结果集为空,描述符区域将仍然包含查询元数据,即字段名称。

If the result set is empty, the Descriptor Area will still contain the metadata from the query, i.e., the field names.

对于尚未执行的已准备好的查询,可以使用 DESCRIBE 语句获取结果集的元数据:

For not yet executed prepared queries, the DESCRIBE statement can be used to get the metadata of the result set:

EXEC SQL BEGIN DECLARE SECTION;
char *sql_stmt = "SELECT * FROM table1";
EXEC SQL END DECLARE SECTION;

EXEC SQL PREPARE stmt1 FROM :sql_stmt;
EXEC SQL DESCRIBE stmt1 INTO SQL DESCRIPTOR mydesc;

在 PostgreSQL 9.0 之前,SQL 关键字是可选的,因此使用 DESCRIPTORSQL DESCRIPTOR 生成了命名的 SQL 描述器区域。而现在它是强制性的,省略 SQL 关键字将生成 SQLDA 描述器区域,请参阅 Section 36.7.2

Before PostgreSQL 9.0, the SQL keyword was optional, so using DESCRIPTOR and SQL DESCRIPTOR produced named SQL Descriptor Areas. Now it is mandatory, omitting the SQL keyword produces SQLDA Descriptor Areas, see Section 36.7.2.

DESCRIBEFETCH 语句中,可以类似地使用 INTOUSING 关键词:它们生成结果集和描述符区域中的元数据。

In DESCRIBE and FETCH statements, the INTO and USING keywords can be used to similarly: they produce the result set and the metadata in a Descriptor Area.

现在,您怎样才能从描述符区域获取数据呢?您可以将描述符区域视为一个带有命名字段的结构。要从页眉中检索字段的值并将其存储到宿主变量中,请使用以下命令:

Now how do you get the data out of the descriptor area? You can think of the descriptor area as a structure with named fields. To retrieve the value of a field from the header and store it into a host variable, use the following command:

EXEC SQL GET DESCRIPTOR name :hostvar = field;

当前,只定义了一个页眉字段:COUNT,它告诉有多少个项目描述符区域(即结果中包含多少列)。宿主变量需要是整数类型。要从项目描述符区域获取字段,请使用以下命令:

Currently, there is only one header field defined: COUNT, which tells how many item descriptor areas exist (that is, how many columns are contained in the result). The host variable needs to be of an integer type. To get a field from the item descriptor area, use the following command:

EXEC SQL GET DESCRIPTOR name VALUE num :hostvar = field;

num 可以是文字整数或包含整数的宿主变量。可能的字段有:

num can be a literal integer or a host variable containing an integer. Possible fields are:

  • CARDINALITY (integer) #

    • number of rows in the result set

  • DATA #

    • actual data item (therefore, the data type of this field depends on the query)

  • DATETIME_INTERVAL_CODE (integer) #

    • When TYPE is 9, DATETIME_INTERVAL_CODE will have a value of 1 for DATE, 2 for TIME, 3 for TIMESTAMP, 4 for TIME WITH TIME ZONE, or 5 for TIMESTAMP WITH TIME ZONE.

  • DATETIME_INTERVAL_PRECISION (integer) #

    • not implemented

  • INDICATOR (integer) #

    • the indicator (indicating a null value or a value truncation)

  • KEY_MEMBER (integer) #

    • not implemented

  • LENGTH (integer) #

    • length of the datum in characters

  • NAME (string) #

    • name of the column

  • NULLABLE (integer) #

    • not implemented

  • OCTET_LENGTH (integer) #

    • length of the character representation of the datum in bytes

  • PRECISION (integer) #

    • precision (for type numeric)

  • RETURNED_LENGTH (integer) #

    • length of the datum in characters

  • RETURNED_OCTET_LENGTH (integer) #

    • length of the character representation of the datum in bytes

  • SCALE (integer) #

    • scale (for type numeric)

  • TYPE (integer) #

    • numeric code of the data type of the column

EXECUTEDECLAREOPEN 语句中, INTOUSING 关键字具有不同的作用。也可以手动构建描述符区域以提供查询或游标的输入参数,而 USING SQL DESCRIPTOR _name_ 则是将输入参数传递到参数化查询中的方法。构建命名 SQL 描述符区域的语句如下:

In EXECUTE, DECLARE and OPEN statements, the effect of the INTO and USING keywords are different. A Descriptor Area can also be manually built to provide the input parameters for a query or a cursor and USING SQL DESCRIPTOR _name_ is the way to pass the input parameters into a parameterized query. The statement to build a named SQL Descriptor Area is below:

EXEC SQL SET DESCRIPTOR name VALUE num field = :hostvar;

PostgreSQL 支持在一个 FETCH 语句中检索多条记录,并且在这种情况下,存储在宿主机变量中的数据假定变量为一个数组。例如:

PostgreSQL supports retrieving more that one record in one FETCH statement and storing the data in host variables in this case assumes that the variable is an array. E.g.:

EXEC SQL BEGIN DECLARE SECTION;
int id[5];
EXEC SQL END DECLARE SECTION;

EXEC SQL FETCH 5 FROM mycursor INTO SQL DESCRIPTOR mydesc;

EXEC SQL GET DESCRIPTOR mydesc VALUE 1 :id = DATA;

36.7.2. SQLDA Descriptor Areas #

SQLDA 描述符区域是一个 C 语言结构,它也可用于获取查询的结果集和元数据。一个结构存储结果集中的一个记录。

An SQLDA Descriptor Area is a C language structure which can be also used to get the result set and the metadata of a query. One structure stores one record from the result set.

EXEC SQL include sqlda.h;
sqlda_t         *mysqlda;

EXEC SQL FETCH 3 FROM mycursor INTO DESCRIPTOR mysqlda;

请注意,SQL 关键字已省略。 Section 36.7.1 中关于 INTOUSING 关键字用例的段落也适用于此,但有一个附加内容。如果使用 INTO 关键字,则可以在 DESCRIBE 语句中完全省略 DESCRIPTOR 关键字:

Note that the SQL keyword is omitted. The paragraphs about the use cases of the INTO and USING keywords in Section 36.7.1 also apply here with an addition. In a DESCRIBE statement the DESCRIPTOR keyword can be completely omitted if the INTO keyword is used:

EXEC SQL DESCRIBE prepared_statement INTO mysqlda;

使用 SQLDA 的程序的一般流如下:

The general flow of a program that uses SQLDA is:

36.7.2.1. SQLDA Data Structure #

SQLDA 使用三种数据结构类型:sqlda_tsqlvar_tstruct sqlname

SQLDA uses three data structure types: sqlda_t, sqlvar_t, and struct sqlname.

Tip

PostgreSQL 的 SQLDA 具有与 IBM DB2 Universal Database 中类似的数据结构,因此有关 DB2 SQLDA 的某些技术信息有助于更好地理解 PostgreSQL 中的 SQLDA。

PostgreSQL’s SQLDA has a similar data structure to the one in IBM DB2 Universal Database, so some technical information on DB2’s SQLDA could help understanding PostgreSQL’s one better.

结构类型 sqlda_t 是实际 SQLDA 的类型。它保存一条记录。并且两个或更多 sqlda_t 结构可以通过 desc_next 字段中的指针连接到链表中,从而表示有序的行集合。因此,当获取两个或更多行时,应用程序可以通过依次读取每个 sqlda_t 节点中的 desc_next 指针来读取这些行。

The structure type sqlda_t is the type of the actual SQLDA. It holds one record. And two or more sqlda_t structures can be connected in a linked list with the pointer in the desc_next field, thus representing an ordered collection of rows. So, when two or more rows are fetched, the application can read them by following the desc_next pointer in each sqlda_t node.

sqlda_t 的定义为:

The definition of sqlda_t is:

struct sqlda_struct
{
    char            sqldaid[8];
    long            sqldabc;
    short           sqln;
    short           sqld;
    struct sqlda_struct *desc_next;
    struct sqlvar_struct sqlvar[1];
};

typedef struct sqlda_struct sqlda_t;

字段的含义为:

The meaning of the fields is:

  • sqldaid #

    • It contains the literal string "SQLDA ".

  • sqldabc #

    • It contains the size of the allocated space in bytes.

  • sqln #

    • It contains the number of input parameters for a parameterized query in case it’s passed into OPEN, DECLARE or EXECUTE statements using the USING keyword. In case it’s used as output of SELECT, EXECUTE or FETCH statements, its value is the same as sqld statement

  • sqld #

    • It contains the number of fields in a result set.

  • desc_next #

    • If the query returns more than one record, multiple linked SQLDA structures are returned, and desc_next holds a pointer to the next entry in the list.

  • sqlvar #

    • This is the array of the columns in the result set.

结构类型 sqlvar_t 保存列值和元数据(例如类型和长度)。该类型的定义为:

The structure type sqlvar_t holds a column value and metadata such as type and length. The definition of the type is:

struct sqlvar_struct
{
    short          sqltype;
    short          sqllen;
    char          *sqldata;
    short         *sqlind;
    struct sqlname sqlname;
};

typedef struct sqlvar_struct sqlvar_t;

字段的含义为:

The meaning of the fields is:

  • sqltype #

    • Contains the type identifier of the field. For values, see enum ECPGttype in ecpgtype.h.

  • sqllen #

    • Contains the binary length of the field. e.g., 4 bytes for ECPGt_int.

  • sqldata #

    • Points to the data. The format of the data is described in Section 36.4.4.

  • sqlind #

    • Points to the null indicator. 0 means not null, -1 means null.

  • sqlname #

    • The name of the field.

一个 struct sqlname 结构保存一个列名。它用作 sqlvar_t 结构的成员。该结构的定义为:

A struct sqlname structure holds a column name. It is used as a member of the sqlvar_t structure. The definition of the structure is:

#define NAMEDATALEN 64

struct sqlname
{
        short           length;
        char            data[NAMEDATALEN];
};

字段的含义为:

The meaning of the fields is:

  • length #

    • Contains the length of the field name.

  • data #

    • Contains the actual field name.

36.7.2.2. Retrieving a Result Set Using an SQLDA #

通过 SQLDA 检索查询结果集的一般步骤如下:

The general steps to retrieve a query result set through an SQLDA are:

以下是一个通过 SQLDA 检索结果集的示例。

Here is an example retrieving a result set through an SQLDA.

首先,声明一个 sqlda_t 结构来接收结果集。

First, declare a sqlda_t structure to receive the result set.

sqlda_t *sqlda1;

接下来,在命令中指定 SQLDA。这是一个 FETCH 命令示例。

Next, specify the SQLDA in a command. This is a FETCH command example.

EXEC SQL FETCH NEXT FROM cur1 INTO DESCRIPTOR sqlda1;

运行一个循环并遵循链表来检索行。

Run a loop following the linked list to retrieve the rows.

sqlda_t *cur_sqlda;

for (cur_sqlda = sqlda1;
     cur_sqlda != NULL;
     cur_sqlda = cur_sqlda->desc_next)
{
    ...
}

在循环内,运行另一个循环来检索行中每列数据(sqlvar_t 结构)。

Inside the loop, run another loop to retrieve each column data (sqlvar_t structure) of the row.

for (i = 0; i < cur_sqlda->sqld; i++)
{
    sqlvar_t v = cur_sqlda->sqlvar[i];
    char *sqldata = v.sqldata;
    short sqllen  = v.sqllen;
    ...
}

要获取一个列值,请检查 sqltype 值(sqlvar_t 结构的成员)。然后,根据列类型转换到合适的方式以从 sqlvar 字段复制数据到宿主变量。

To get a column value, check the sqltype value, a member of the sqlvar_t structure. Then, switch to an appropriate way, depending on the column type, to copy data from the sqlvar field to a host variable.

char var_buf[1024];

switch (v.sqltype)
{
    case ECPGt_char:
        memset(&var_buf, 0, sizeof(var_buf));
        memcpy(&var_buf, sqldata, (sizeof(var_buf) <= sqllen ? sizeof(var_buf) - 1 : sqllen));
        break;

    case ECPGt_int: /* integer */
        memcpy(&intval, sqldata, sqllen);
        snprintf(var_buf, sizeof(var_buf), "%d", intval);
        break;

    ...
}

36.7.2.3. Passing Query Parameters Using an SQLDA #

通过 SQLDA 将输入参数传递给已准备查询的一般步骤如下:

The general steps to use an SQLDA to pass input parameters to a prepared query are:

以下是一个示例。

Here is an example.

首先,创建一个已准备好的语句。

First, create a prepared statement.

EXEC SQL BEGIN DECLARE SECTION;
char query[1024] = "SELECT d.oid, * FROM pg_database d, pg_stat_database s WHERE d.oid = s.datid AND (d.datname = ? OR d.oid = ?)";
EXEC SQL END DECLARE SECTION;

EXEC SQL PREPARE stmt1 FROM :query;

接下来,为 SQLDA 分配内存,并设置 sqln 中的输入参数数,该参数是 sqlda_t 结构的一个成员变量。当准备的查询需要两个或更多个输入参数时,应用程序必须分配额外的内存空间,按(参数数 - 1)* sizeof(sqlvar_t) 计算。此处显示的示例为两个输入参数分配了内存空间。

Next, allocate memory for an SQLDA, and set the number of input parameters in sqln, a member variable of the sqlda_t structure. When two or more input parameters are required for the prepared query, the application has to allocate additional memory space which is calculated by (nr. of params - 1) * sizeof(sqlvar_t). The example shown here allocates memory space for two input parameters.

sqlda_t *sqlda2;

sqlda2 = (sqlda_t *) malloc(sizeof(sqlda_t) + sizeof(sqlvar_t));
memset(sqlda2, 0, sizeof(sqlda_t) + sizeof(sqlvar_t));

sqlda2->sqln = 2; /* number of input variables */

在内存分配后,将参数值存储到 sqlvar[] 数组中。(这是在 SQLDA 接收结果集时用来检索列值的同一数组。)在此示例中,输入参数是 "postgres"(具有字符串类型)和 1(具有整数类型)。

After memory allocation, store the parameter values into the sqlvar[] array. (This is same array used for retrieving column values when the SQLDA is receiving a result set.) In this example, the input parameters are "postgres", having a string type, and 1, having an integer type.

sqlda2->sqlvar[0].sqltype = ECPGt_char;
sqlda2->sqlvar[0].sqldata = "postgres";
sqlda2->sqlvar[0].sqllen  = 8;

int intval = 1;
sqlda2->sqlvar[1].sqltype = ECPGt_int;
sqlda2->sqlvar[1].sqldata = (char *) &intval;
sqlda2->sqlvar[1].sqllen  = sizeof(intval);

通过打开一个游标并指明事先设置好的 SQLDA,输入参数会被传送到已准备好的语句。

By opening a cursor and specifying the SQLDA that was set up beforehand, the input parameters are passed to the prepared statement.

EXEC SQL OPEN cur1 USING DESCRIPTOR sqlda2;

最后,在用过输入 SQLDA 之后,必须显式释放分配的内存空间,这与用来接收查询结果的 SQLDA 不同。

Finally, after using input SQLDAs, the allocated memory space must be freed explicitly, unlike SQLDAs used for receiving query results.

free(sqlda2);

36.7.2.4. A Sample Application Using SQLDA #

以下是一个示例程序,它描述如何从系统目录中提取由输入参数指定数据库的访问统计信息。

Here is an example program, which describes how to fetch access statistics of the databases, specified by the input parameters, from the system catalogs.

此应用程序通过数据库 OID 联接两个系统表,pg_database 和 pg_stat_database,并且还提取并显示由两个输入参数(一个数据库 postgres 和 OID 1)检索到的数据库统计信息。

This application joins two system tables, pg_database and pg_stat_database on the database OID, and also fetches and shows the database statistics which are retrieved by two input parameters (a database postgres, and OID 1).

首先,声明一个用于输入的 SQLDA 和一个用于输出的 SQLDA。

First, declare an SQLDA for input and an SQLDA for output.

EXEC SQL include sqlda.h;

sqlda_t *sqlda1; /* an output descriptor */
sqlda_t *sqlda2; /* an input descriptor  */

接下来,连接到数据库,准备一条语句,并声明一个针对已准备好的语句的游标。

Next, connect to the database, prepare a statement, and declare a cursor for the prepared statement.

int
main(void)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char query[1024] = "SELECT d.oid,* FROM pg_database d, pg_stat_database s WHERE d.oid=s.datid AND ( d.datname=? OR d.oid=? )";
    EXEC SQL END DECLARE SECTION;

    EXEC SQL CONNECT TO testdb AS con1 USER testuser;
    EXEC SQL SELECT pg_catalog.set_config('search_path', '', false); EXEC SQL COMMIT;

    EXEC SQL PREPARE stmt1 FROM :query;
    EXEC SQL DECLARE cur1 CURSOR FOR stmt1;

接下来,为输入参数将一些值填入输入 SQLDA。为输入 SQLDA 分配内存,并将输入参数数设置成 sqln。将类型、值和值长度存储到 sqltypesqldatasqllen 中的 sqlvar 结构中。

Next, put some values in the input SQLDA for the input parameters. Allocate memory for the input SQLDA, and set the number of input parameters to sqln. Store type, value, and value length into sqltype, sqldata, and sqllen in the sqlvar structure.

    /* Create SQLDA structure for input parameters. */
    sqlda2 = (sqlda_t *) malloc(sizeof(sqlda_t) + sizeof(sqlvar_t));
    memset(sqlda2, 0, sizeof(sqlda_t) + sizeof(sqlvar_t));
    sqlda2->sqln = 2; /* number of input variables */

    sqlda2->sqlvar[0].sqltype = ECPGt_char;
    sqlda2->sqlvar[0].sqldata = "postgres";
    sqlda2->sqlvar[0].sqllen  = 8;

    intval = 1;
    sqlda2->sqlvar[1].sqltype = ECPGt_int;
    sqlda2->sqlvar[1].sqldata = (char *)&intval;
    sqlda2->sqlvar[1].sqllen  = sizeof(intval);

在设置好输入 SQLDA 后,通过输入 SQLDA 打开一个游标。

After setting up the input SQLDA, open a cursor with the input SQLDA.

    /* Open a cursor with input parameters. */
    EXEC SQL OPEN cur1 USING DESCRIPTOR sqlda2;

从打开的游标中提取行到输出 SQLDA 中。(通常,必须在循环中重复调用 FETCH,以提取结果集中的所有行。)

Fetch rows into the output SQLDA from the opened cursor. (Generally, you have to call FETCH repeatedly in the loop, to fetch all rows in the result set.)

    while (1)
    {
        sqlda_t *cur_sqlda;

        /* Assign descriptor to the cursor  */
        EXEC SQL FETCH NEXT FROM cur1 INTO DESCRIPTOR sqlda1;

接下来,通过遵循 sqlda_t 结构的链接列表,从 SQLDA 中检索提取的记录。

Next, retrieve the fetched records from the SQLDA, by following the linked list of the sqlda_t structure.

    for (cur_sqlda = sqlda1 ;
         cur_sqlda != NULL ;
         cur_sqlda = cur_sqlda->desc_next)
    {
        ...

读取第一条记录中的各列。列数存储在 sqld 中,第一列的实际数据存储在 sqlvar[0] 中,这两者都是 sqlda_t 结构的成员。

Read each columns in the first record. The number of columns is stored in sqld, the actual data of the first column is stored in sqlvar[0], both members of the sqlda_t structure.

        /* Print every column in a row. */
        for (i = 0; i < sqlda1->sqld; i++)
        {
            sqlvar_t v = sqlda1->sqlvar[i];
            char *sqldata = v.sqldata;
            short sqllen  = v.sqllen;

            strncpy(name_buf, v.sqlname.data, v.sqlname.length);
            name_buf[v.sqlname.length] = '\0';

现在,列数据存储在变量 v 中。根据 v.sqltype 中列的类型,将每个数据项复制到主机变量中。

Now, the column data is stored in the variable v. Copy every datum into host variables, looking at v.sqltype for the type of the column.

            switch (v.sqltype) {
                int intval;
                double doubleval;
                unsigned long long int longlongval;

                case ECPGt_char:
                    memset(&var_buf, 0, sizeof(var_buf));
                    memcpy(&var_buf, sqldata, (sizeof(var_buf) <= sqllen ? sizeof(var_buf)-1 : sqllen));
                    break;

                case ECPGt_int: /* integer */
                    memcpy(&intval, sqldata, sqllen);
                    snprintf(var_buf, sizeof(var_buf), "%d", intval);
                    break;

                ...

                default:
                    ...
            }

            printf("%s = %s (type: %d)\n", name_buf, var_buf, v.sqltype);
        }

在处理完所有记录后关闭游标,并断开与数据库的连接。

Close the cursor after processing all of records, and disconnect from the database.

    EXEC SQL CLOSE cur1;
    EXEC SQL COMMIT;

    EXEC SQL DISCONNECT ALL;

完整的程序显示在 Example 36.1 中。

The whole program is shown in Example 36.1.

Example 36.1. Example SQLDA Program

#include <stdlib.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>

EXEC SQL include sqlda.h;

sqlda_t *sqlda1; /* descriptor for output */
sqlda_t *sqlda2; /* descriptor for input */

EXEC SQL WHENEVER NOT FOUND DO BREAK;
EXEC SQL WHENEVER SQLERROR STOP;

int
main(void)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char query[1024] = "SELECT d.oid,* FROM pg_database d, pg_stat_database s WHERE d.oid=s.datid AND ( d.datname=? OR d.oid=? )";

    int intval;
    unsigned long long int longlongval;
    EXEC SQL END DECLARE SECTION;

    EXEC SQL CONNECT TO uptimedb AS con1 USER uptime;
    EXEC SQL SELECT pg_catalog.set_config('search_path', '', false); EXEC SQL COMMIT;

    EXEC SQL PREPARE stmt1 FROM :query;
    EXEC SQL DECLARE cur1 CURSOR FOR stmt1;

    /* Create an SQLDA structure for an input parameter */
    sqlda2 = (sqlda_t *)malloc(sizeof(sqlda_t) + sizeof(sqlvar_t));
    memset(sqlda2, 0, sizeof(sqlda_t) + sizeof(sqlvar_t));
    sqlda2->sqln = 2; /* a number of input variables */

    sqlda2->sqlvar[0].sqltype = ECPGt_char;
    sqlda2->sqlvar[0].sqldata = "postgres";
    sqlda2->sqlvar[0].sqllen  = 8;

    intval = 1;
    sqlda2->sqlvar[1].sqltype = ECPGt_int;
    sqlda2->sqlvar[1].sqldata = (char *) &intval;
    sqlda2->sqlvar[1].sqllen  = sizeof(intval);

    /* Open a cursor with input parameters. */
    EXEC SQL OPEN cur1 USING DESCRIPTOR sqlda2;

    while (1)
    {
        sqlda_t *cur_sqlda;

        /* Assign descriptor to the cursor  */
        EXEC SQL FETCH NEXT FROM cur1 INTO DESCRIPTOR sqlda1;

        for (cur_sqlda = sqlda1 ;
             cur_sqlda != NULL ;
             cur_sqlda = cur_sqlda->desc_next)
        {
            int i;
            char name_buf[1024];
            char var_buf[1024];

            /* Print every column in a row. */
            for (i=0 ; i<cur_sqlda->sqld ; i++)
            {
                sqlvar_t v = cur_sqlda->sqlvar[i];
                char *sqldata = v.sqldata;
                short sqllen  = v.sqllen;

                strncpy(name_buf, v.sqlname.data, v.sqlname.length);
                name_buf[v.sqlname.length] = '\0';

                switch (v.sqltype)
                {
                    case ECPGt_char:
                        memset(&var_buf, 0, sizeof(var_buf));
                        memcpy(&var_buf, sqldata, (sizeof(var_buf)<=sqllen ? sizeof(var_buf)-1 : sqllen) );
                        break;

                    case ECPGt_int: /* integer */
                        memcpy(&intval, sqldata, sqllen);
                        snprintf(var_buf, sizeof(var_buf), "%d", intval);
                        break;

                    case ECPGt_long_long: /* bigint */
                        memcpy(&longlongval, sqldata, sqllen);
                        snprintf(var_buf, sizeof(var_buf), "%lld", longlongval);
                        break;

                    default:
                    {
                        int i;
                        memset(var_buf, 0, sizeof(var_buf));
                        for (i = 0; i < sqllen; i++)
                        {
                            char tmpbuf[16];
                            snprintf(tmpbuf, sizeof(tmpbuf), "%02x ", (unsigned char) sqldata[i]);
                            strncat(var_buf, tmpbuf, sizeof(var_buf));
                        }
                    }
                        break;
                }

                printf("%s = %s (type: %d)\n", name_buf, var_buf, v.sqltype);
            }

            printf("\n");
        }
    }

    EXEC SQL CLOSE cur1;
    EXEC SQL COMMIT;

    EXEC SQL DISCONNECT ALL;

    return 0;
}

此例的输出应类似于以下内容(部分数字会有所不同)。

The output of this example should look something like the following (some numbers will vary).

oid = 1 (type: 1)
datname = template1 (type: 1)
datdba = 10 (type: 1)
encoding = 0 (type: 5)
datistemplate = t (type: 1)
datallowconn = t (type: 1)
datconnlimit = -1 (type: 5)
datfrozenxid = 379 (type: 1)
dattablespace = 1663 (type: 1)
datconfig =  (type: 1)
datacl = {=c/uptime,uptime=CTc/uptime} (type: 1)
datid = 1 (type: 1)
datname = template1 (type: 1)
numbackends = 0 (type: 5)
xact_commit = 113606 (type: 9)
xact_rollback = 0 (type: 9)
blks_read = 130 (type: 9)
blks_hit = 7341714 (type: 9)
tup_returned = 38262679 (type: 9)
tup_fetched = 1836281 (type: 9)
tup_inserted = 0 (type: 9)
tup_updated = 0 (type: 9)
tup_deleted = 0 (type: 9)

oid = 11511 (type: 1)
datname = postgres (type: 1)
datdba = 10 (type: 1)
encoding = 0 (type: 5)
datistemplate = f (type: 1)
datallowconn = t (type: 1)
datconnlimit = -1 (type: 5)
datfrozenxid = 379 (type: 1)
dattablespace = 1663 (type: 1)
datconfig =  (type: 1)
datacl =  (type: 1)
datid = 11511 (type: 1)
datname = postgres (type: 1)
numbackends = 0 (type: 5)
xact_commit = 221069 (type: 9)
xact_rollback = 18 (type: 9)
blks_read = 1176 (type: 9)
blks_hit = 13943750 (type: 9)
tup_returned = 77410091 (type: 9)
tup_fetched = 3253694 (type: 9)
tup_inserted = 0 (type: 9)
tup_updated = 0 (type: 9)
tup_deleted = 0 (type: 9)