| PostgreSQL Reference Manual - Volume 2 - Programming Guide by The PostgreSQL Global Development Group Paperback (6"x9"), 408 pages ISBN 0954612035 RRP £19.95 ($34.95) Sales of this book support the PostgreSQL project! Get a printed copy>>> |
1.3.1 Main Functions
PQexec-
Submits a command to the server
and waits for the result.
PGresult *PQexec(PGconn *conn, const char *command);
Returns aPGresultpointer or possibly a null pointer. A non-null pointer will generally be returned except in out-of-memory conditions or serious errors such as inability to send the command to the server. If a null pointer is returned, it should be treated like aPGRES_FATAL_ERRORresult. UsePQerrorMessageto get more information about such errors.
It is allowed to include multiple SQL commands (separated by semicolons) in
the command string. Multiple queries sent in a single PQexec
call are processed in a single transaction, unless there are explicit
BEGIN/COMMIT commands included in the query string to divide it into multiple
transactions. Note however that the returned PGresult
structure describes only the result of the last command executed from the
string. Should one of the commands fail, processing of the string stops with
it and the returned PGresult describes the error
condition.
PQexecParams-
Submits a command to the server and waits for the result,
with the ability to pass parameters separately from the SQL
command text.
PGresult *PQexecParams(PGconn *conn, const char *command, int nParams, const Oid *paramTypes, const char * const *paramValues, const int *paramLengths, const int *paramFormats, int resultFormat);PQexecParamsis likePQexec, but offers additional functionality: parameter values can be specified separately from the command string proper, and query results can be requested in either text or binary format.PQexecParamsis supported only in protocol 3.0 and later connections; it will fail when using protocol 2.0. The function arguments are:conn- The connection object to send the command through.
command-
The SQL command string to be executed. If parameters are used, they are
referred to in the command string as
$1,$2, etc. nParams-
The number of parameters supplied; it is the length of the arrays
paramTypes[],paramValues[],paramLengths[], andparamFormats[]. (The array pointers may beNULLwhennParamsis zero.) paramTypes[]-
Specifies, by OID, the data types to be assigned to the parameter
symbols. If
paramTypesisNULL, or any particular element in the array is zero, the server infers a data type for the parameter symbol in the same way it would do for an untyped literal string. paramValues[]- Specifies the actual values of the parameters. A null pointer in this array means the corresponding parameter is null; otherwise the pointer points to a zero-terminated text string (for text format) or binary data in the format expected by the server (for binary format).
paramLengths[]- Specifies the actual data lengths of binary-format parameters. It is ignored for null parameters and text-format parameters. The array pointer may be null when there are no binary parameters.
paramFormats[]- Specifies whether parameters are text (put a zero in the array entry for the corresponding parameter) or binary (put a one in the array entry for the corresponding parameter). If the array pointer is null then all parameters are presumed to be text strings.
resultFormat- Specify zero to obtain results in text format, or one to obtain results in binary format. (There is not currently a provision to obtain different result columns in different formats, although that is possible in the underlying protocol.)
The primary advantage of PQexecParams over PQexec
is that parameter values may be separated from the command string, thus
avoiding the need for tedious and error-prone quoting and escaping.
Unlike PQexec, PQexecParams allows at most one SQL
command in the given string. (There can be semicolons in it, but not more
than one nonempty command.) This is a limitation of the underlying protocol,
but has some usefulness as an extra defense against SQL-injection attacks.
Tip: Specifying parameter types via OIDs is tedious, particularly if you prefer not to hard-wire particular OID values into your program. However, you can avoid doing so even in cases where the server by itself cannot determine the type of the parameter, or chooses a different type than you want. In the SQL command text, attach an explicit cast to the parameter symbol to show what data type you will send. For example,
select * from mytable where x = $1::bigint;This forces parameter
$1to be treated asbigint, whereas by default it would be assigned the same type asx. Forcing the parameter type decision, either this way or by specifying a numeric type OID, is strongly recommended when sending parameter values in binary format, because binary format has less redundancy than text format and so there is less chance that the server will detect a type mismatch mistake for you.
PQprepare-
Submits a request to create a prepared statement with the
given parameters, and waits for completion.
PGresult *PQprepare(PGconn *conn, const char *stmtName, const char *query, int nParams, const Oid *paramTypes);PQpreparecreates a prepared statement for later execution withPQexecPrepared. This feature allows commands that will be used repeatedly to be parsed and planned just once, rather than each time they are executed.PQprepareis supported only in protocol 3.0 and later connections; it will fail when using protocol 2.0. The function creates a prepared statement namedstmtNamefrom thequerystring, which must contain a single SQL command.stmtNamemay be""to create an unnamed statement, in which case any pre-existing unnamed statement is automatically replaced; otherwise it is an error if the statement name is already defined in the current session. If any parameters are used, they are referred to in the query as$1,$2, etc.nParamsis the number of parameters for which types are pre-specified in the arrayparamTypes[]. (The array pointer may beNULLwhennParamsis zero.)paramTypes[]specifies, by OID, the data types to be assigned to the parameter symbols. IfparamTypesisNULL, or any particular element in the array is zero, the server assigns a data type to the parameter symbol in the same way it would do for an untyped literal string. Also, the query may use parameter symbols with numbers higher thannParams; data types will be inferred for these symbols as well. (SeePQdescribePreparedfor a means to find out what data types were inferred.) As withPQexec, the result is normally aPGresultobject whose contents indicate server-side success or failure. A null result indicates out-of-memory or inability to send the command at all. UsePQerrorMessageto get more information about such errors.
Prepared statements for use with PQexecPrepared can also
be created by executing SQL PREPARE statements. (But PQprepare
is more flexible since it does not require parameter types to be
pre-specified.) Also, although there is no libpq
function for deleting a prepared statement, the SQL DEALLOCATE statement can
be used for that purpose.
PQexecPrepared-
Sends a request to execute a prepared statement with given
parameters, and waits for the result.
PGresult *PQexecPrepared(PGconn *conn, const char *stmtName, int nParams, const char * const *paramValues, const int *paramLengths, const int *paramFormats, int resultFormat);PQexecPreparedis likePQexecParams, but the command to be executed is specified by naming a previously-prepared statement, instead of giving a query string. This feature allows commands that will be used repeatedly to be parsed and planned just once, rather than each time they are executed. The statement must have been prepared previously in the current session.PQexecPreparedis supported only in protocol 3.0 and later connections; it will fail when using protocol 2.0. The parameters are identical toPQexecParams, except that the name of a prepared statement is given instead of a query string, and theparamTypes[]parameter is not present (it is not needed since the prepared statement's parameter types were determined when it was created). PQdescribePrepared-
Submits a request to obtain information about the specified
prepared statement, and waits for completion.
PGresult *PQdescribePrepared(PGconn *conn, const char *stmtName);
PQdescribePreparedallows an application to obtain information about a previously prepared statement.PQdescribePreparedis supported only in protocol 3.0 and later connections; it will fail when using protocol 2.0.stmtNamemay be""or NULL to reference the unnamed statement, otherwise it must be the name of an existing prepared statement. On success, aPGresultwith statusPGRES_COMMAND_OKis returned. The functionsPQnparamsandPQparamtypemay be applied to thisPGresultto obtain information about the parameters of the prepared statement, and the functionsPQnfields,PQfname,PQftype, etc provide information about the result columns (if any) of the statement. PQdescribePortal-
Submits a request to obtain information about the specified
portal, and waits for completion.
PGresult *PQdescribePortal(PGconn *conn, const char *portalName);
PQdescribePortalallows an application to obtain information about a previously created portal. (libpq does not provide any direct access to portals, but you can use this function to inspect the properties of a cursor created with aDECLARE CURSORSQL command.)PQdescribePortalis supported only in protocol 3.0 and later connections; it will fail when using protocol 2.0.portalNamemay be""or NULL to reference the unnamed portal, otherwise it must be the name of an existing portal. On success, aPGresultwith statusPGRES_COMMAND_OKis returned. The functionsPQnfields,PQfname,PQftype, etc may be applied to thePGresultto obtain information about the result columns (if any) of the portal.
The
PGresult
structure encapsulates the result returned by the server.
libpq application programmers should be
careful to maintain the PGresult abstraction.
Use the accessor functions below to get at the contents of
PGresult. Avoid directly referencing the
fields of the PGresult structure because they
are subject to change in the future.
PQresultStatus-
Returns the result status of the command.
ExecStatusType PQresultStatus(const PGresult *res);
PQresultStatuscan return one of the following values:PGRES_EMPTY_QUERY- The string sent to the server was empty.
PGRES_COMMAND_OK- Successful completion of a command returning no data.
PGRES_TUPLES_OK-
Successful completion of a command returning data (such as
a
SELECTorSHOW). PGRES_COPY_OUT- Copy Out (from server) data transfer started.
PGRES_COPY_IN- Copy In (to server) data transfer started.
PGRES_BAD_RESPONSE- The server's response was not understood.
PGRES_NONFATAL_ERROR- A nonfatal error (a notice or warning) occurred.
PGRES_FATAL_ERROR- A fatal error occurred.
PGRES_TUPLES_OK, then the functions described below can be used to retrieve the rows returned by the query. Note that aSELECTcommand that happens to retrieve zero rows still showsPGRES_TUPLES_OK.PGRES_COMMAND_OKis for commands that can never return rows (INSERT,UPDATE, etc.). A response ofPGRES_EMPTY_QUERYmay indicate a bug in the client software. A result of statusPGRES_NONFATAL_ERRORwill never be returned directly byPQexecor other query execution functions; results of this kind are instead passed to the notice processor (see section 1.11 Notice Processing). PQresStatus-
Converts the enumerated type returned by
PQresultStatusinto a string constant describing the status code. The caller should not free the result.char *PQresStatus(ExecStatusType status);
PQresultErrorMessage-
Returns the error message associated with the command, or an empty string
if there was no error.
char *PQresultErrorMessage(const PGresult *res);
If there was an error, the returned string will include a trailing newline. The caller should not free the result directly. It will be freed when the associatedPGresulthandle is passed toPQclear. Immediately following aPQexecorPQgetResultcall,PQerrorMessage(on the connection) will return the same string asPQresultErrorMessage(on the result). However, aPGresultwill retain its error message until destroyed, whereas the connection's error message will change when subsequent operations are done. UsePQresultErrorMessagewhen you want to know the status associated with a particularPGresult; usePQerrorMessagewhen you want to know the status from the latest operation on the connection. PQresultErrorField-
Returns an individual field of an error report.
char *PQresultErrorField(const PGresult *res, int fieldcode);
fieldcodeis an error field identifier; see the symbols listed below.NULLis returned if thePGresultis not an error or warning result, or does not include the specified field. Field values will normally not include a trailing newline. The caller should not free the result directly. It will be freed when the associatedPGresulthandle is passed toPQclear. The following field codes are available:PG_DIAG_SEVERITY-
The severity; the field contents are
ERROR,FATAL, orPANIC(in an error message), orWARNING,NOTICE,DEBUG,INFO, orLOG(in a notice message), or a localized translation of one of these. Always present. PG_DIAG_SQLSTATE- The SQLSTATE code for the error. The SQLSTATE code identifies the type of error that has occurred; it can be used by front-end applications to perform specific operations (such as error handling) in response to a particular database error. For a list of the possible SQLSTATE codes, see Volume 1: A PostgreSQL Error Codes. This field is not localizable, and is always present.
PG_DIAG_MESSAGE_PRIMARY- The primary human-readable error message (typically one line). Always present.
PG_DIAG_MESSAGE_DETAIL- Detail: an optional secondary error message carrying more detail about the problem. May run to multiple lines.
PG_DIAG_MESSAGE_HINT- Hint: an optional suggestion what to do about the problem. This is intended to differ from detail in that it offers advice (potentially inappropriate) rather than hard facts. May run to multiple lines.
PG_DIAG_STATEMENT_POSITION- A string containing a decimal integer indicating an error cursor position as an index into the original statement string. The first character has index 1, and positions are measured in characters not bytes.
PG_DIAG_INTERNAL_POSITION-
This is defined the same as the
PG_DIAG_STATEMENT_POSITIONfield, but it is used when the cursor position refers to an internally generated command rather than the one submitted by the client. ThePG_DIAG_INTERNAL_QUERYfield will always appear when this field appears. PG_DIAG_INTERNAL_QUERY- The text of a failed internally-generated command. This could be, for example, a SQL query issued by a PL/pgSQL function.
PG_DIAG_CONTEXT- An indication of the context in which the error occurred. Presently this includes a call stack traceback of active procedural language functions and internally-generated queries. The trace is one entry per line, most recent first.
PG_DIAG_SOURCE_FILE- The file name of the source-code location where the error was reported.
PG_DIAG_SOURCE_LINE- The line number of the source-code location where the error was reported.
PG_DIAG_SOURCE_FUNCTION- The name of the source-code function reporting the error.
PGresultobjects, notPGconnobjects; there is noPQerrorFieldfunction. PQclear-
Frees the storage associated with a
PGresult. Every command result should be freed viaPQclearwhen it is no longer needed.void PQclear(PGresult *res);
You can keep aPGresultobject around for as long as you need it; it does not go away when you issue a new command, nor even if you close the connection. To get rid of it, you must callPQclear. Failure to do this will result in memory leaks in your application. PQmakeEmptyPGresult-
Constructs an empty
PGresultobject with the given status.PGresult *PQmakeEmptyPGresult(PGconn *conn, ExecStatusType status);
This is libpq's internal function to allocate and initialize an emptyPGresultobject. This function returns NULL if memory could not be allocated. It is exported because some applications find it useful to generate result objects (particularly objects with error status) themselves. Ifconnis not null andstatusindicates an error, the current error message of the specified connection is copied into thePGresult. Note thatPQclearshould eventually be called on the object, just as with aPGresultreturned by libpq itself.
| ISBN 0954612035 | PostgreSQL Reference Manual - Volume 2 - Programming Guide | See the print edition |