pg_exec
Prev | 4.3. Query Execution Commands | Next

## pg_exec

pg_exec — Execute an SQL command on the server

## Synopsis

    pg_exec conn commandString ?param...?

## Description

`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.

## Arguments

`conn`

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

`commandString`

  The SQL command to execute.

`param...`

  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.

## Notes

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.

Prev | Up | Next
4.3. Query Execution Commands | Home | pg_execute