pg_exec — Execute an SQL command on the server


pg_exec conn commandString ?param...?


pg_exec sends a command to the PostgreSQL server and returns a result handle. Optional arguments can be supplied to replace parameter place-holders in the command string.



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


The SQL command to execute.


Zero or more parameter values to bind to command string place-holders. The first parameter will replace $1 in the command string, the second parameter will replace $2, etc.

Return Value

Returns a result handle which can be used with pg_result to obtain the results of the command.

A Tcl error will be thrown if an error occurs communicating with the database. Note that no Tcl error will be thrown if an invalid command is successfully sent to the server and a response successfully received. The result status must be checked after a normal return.


Be sure to free the returned result handle with pg_result -clear when you are done with it.

pg_exec can be used to start a COPY, after which the application reads directly from or writes directly to the connection handle. See Section 5.13, “Example - COPY FROM and COPY TO” for an example.

If optional arguments are supplied, this command becomes a simplified form of pg_exec_params, supporting only text-format arguments with a text-format result. The command string must include parameter place-holders $1, $2, etc. and an equal number of parameter arguments. Be sure to brace-quote or escape the parameter place-holders such as $1 in the SQL command string to protect them from Tcl variable expansion. Use of these parameters avoids the need to quote and escape values which would otherwise have to be substituted directly into the command string.

The form of this command using optional arguments for parameterized queries was added in pgtclng-1.5.1 and in pgintcl-2.1.0.

This command uses or emulates the PostgreSQL libpq function PQexec if called without optional query parameter arguments, and the function PQexecParams if called with optional query parameter arguments. 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.