PGresult *PQprepare(PGconn *conn,
const char *stmtName,
const char *query,
int nParams,
const Oid *paramTypes);
PQprepare 创建一个准备好的语句,供以后使用 PQexecPrepared 执行。该特性允许命令重复执行,无需每次都进行解析和规划;有关详细信息,请参阅准备。PQprepare creates a prepared statement for later execution with PQexecPrepared. This feature allows commands to be executed repeatedly without being parsed and planned each time; see PREPARE for details.
该函数根据查询字符串创建一个名为 stmtName 的预准备语句,该语句必须包含一个 SQL 命令。 stmtName 可以是 “” 来创建一个未命名的语句,在这种情况下,任何预先存在的未命名语句都会被自动替换;否则,如果当前会话中已经定义了语句名称,则会出错。如果使用任何参数,它们在查询中称为 $1、$2 等。nParams 是在数组 paramTypes[] 中预先指定类型的参数的数量。 (当 nParams 为零时,数组指针可以为 NULL。) paramTypes[] 通过 OID 指定要分配给参数符号的数据类型。如果 paramTypes 为 NULL,或者数组中的任何特定元素为零,则服务器将数据类型分配给参数符号,就像它为无类型文字字符串所做的那样。此外,查询可以使用数字大于 nParams 的参数符号;还将为这些符号推断数据类型。 (请参阅 PQdescribePrepared 了解推断出哪些数据类型的方法。)The function creates a prepared statement named stmtName from the query string, which must contain a single SQL command. stmtName can 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. nParams is the number of parameters for which types are pre-specified in the array paramTypes[]. (The array pointer can be NULL when nParams is zero.) paramTypes[] specifies, by OID, the data types to be assigned to the parameter symbols. If paramTypes is NULL, 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 can use parameter symbols with numbers higher than nParams; data types will be inferred for these symbols as well. (See PQdescribePrepared for a means to find out what data types were inferred.)
与 PQexec 一样,结果通常是一个 PGresult 对象,其内容指示服务器端成功或失败。空结果表示内存不足或根本无法发送命令。使用 PQerrorMessage 获取有关此类错误的更多信息。As with PQexec, the result is normally a PGresult object whose contents indicate server-side success or failure. A null result indicates out-of-memory or inability to send the command at all. Use PQerrorMessage to get more information about such errors.
也可以通过执行 SQL PREPARE 语句来创建用于 PQexecPrepared 的预处理语句。此外,虽然没有用于删除准备好的语句的 libpq 函数,但 SQL DEALLOCATE 语句可用于此目的。Prepared statements for use with PQexecPrepared can also be created by executing SQL PREPARE statements. Also, although there is no libpq function for deleting a prepared statement, the SQL DEALLOCATE statement can be used for that purpose.