pg_select

pg_select — Execute an SQL command on the server and loop over the results

Synopsis

pg_select conn commandString arrayVar procedure

Description

pg_select submits a query (SELECT statement) to the PostgreSQL server and executes a given chunk of code for each row in the result. The commandString must be a SELECT statement; anything else returns an error. The arrayVar variable is an array name used in the loop. For each row, arrayVar is filled in with the row values, using the column names as the array indices. Then the procedure is executed.

In addition to the column values, the following special entries are made in the array:

.headers

A list of the column names returned by the query.

.numcols

The number of columns returned by the query.

.tupno

The current row number, starting at zero and incrementing for each iteration of the loop body.

Arguments

conn

The handle of the connection on which to execute the command.

commandString

The SQL query to execute.

arrayVar

An array variable for returned rows.

procedure

The procedure or script to run for each returned row.

Return Value

None

A Tcl error will be thrown if an error occurs communicating with the database, or if there is an error processing the query, or if the procedure body throws a Tcl error.

Notes

pg_execute is a newer command which provides more features and is more flexible than pg_select.

This command uses or emulates the PostgreSQL libpq function PQexec.

Examples

This examples assumes that the table table1 has columns control and name (and perhaps others):

pg_select $conn "SELECT * FROM table1" array {
    puts [format "%5d %s" $array(control) $array(name)]
}

SourceForge.net Logo

This version of the manual was produced for the Pgtcl-ng Sourceforge project web service site, which requires the logo on each page.

To download a logo-free copy of the manual, see the Pgtcl-ng project downloads area.