📄 libpq.sgml
字号:
<Chapter Id="libpq-chapter"><Title id="libpq">libpq</Title><Para><FileName>libpq</FileName> is the C application programmer's interface to<ProductName>Postgres</ProductName>. <FileName>libpq</FileName> is a setof library routines that allow client programs to pass queries to the<ProductName>Postgres</ProductName> backend server and to receive theresults of these queries. <FileName>libpq</FileName> is also theunderlying engine for several other <ProductName>Postgres</ProductName>application interfaces, including <FileName>libpq++</FileName> (C++),<FileName>libpgtcl</FileName> (Tcl), <FileName>perl5</FileName>, and<FileName>ecpg</FileName>. So some aspects of libpq's behavior will beimportant to you if you use one of those packages.Three short programs are included at the end of this section to show howto write programs that use <FileName>libpq</FileName>. There are severalcomplete examples of <FileName>libpq</FileName> applications in thefollowing directories:<ProgramListing> ../src/test/regress ../src/test/examples ../src/bin/psql</ProgramListing></Para><Para>Frontend programs which use <FileName>libpq</FileName> must include theheader file <FileName>libpq-fe.h</FileName> and must link with the<FileName>libpq</FileName> library.</Para><Sect1><Title>Database Connection Functions</Title><Para> The following routines deal with making a connection to a <ProductName>Postgres</ProductName> backend server. The application program can have several backend connections open at one time. (One reason to do that is to access more than one database.) Each connection is represented by a PGconn object which is obtained from PQconnectdb() or PQsetdbLogin(). NOTE that these functions will always return a non-null object pointer, unless perhaps there is too little memory even to allocate the PGconn object. The PQstatus function should be called to check whether a connection was successfully made before queries are sent via the connection object.<ItemizedList><ListItem><Para><Function>PQsetdbLogin</Function> Makes a new connection to a backend.<synopsis>PGconn *PQsetdbLogin(const char *pghost, const char *pgport, const char *pgoptions, const char *pgtty, const char *dbName, const char *login, const char *pwd)</synopsis> If any argument is NULL, then the corresponding environment variable (see "Environment Variables" section) is checked. If the environment variable is also not set, then hardwired defaults are used. The return value is a pointer to an abstract struct representing the connection to the backend.</Para></ListItem><ListItem><Para><Function>PQsetdb</Function> Makes a new connection to a backend.<synopsis>PGconn *PQsetdb(char *pghost, char *pgport, char *pgoptions, char *pgtty, char *dbName)</synopsis> This is a macro that calls PQsetdbLogin() with null pointers for the login and pwd parameters. It is provided primarily for backward compatibility with old programs.</Para></ListItem><ListItem><Para><Function>PQconnectdb</Function> Makes a new connection to a backend.<synopsis>PGconn *PQconnectdb(const char *conninfo)</synopsis> This routine opens a new database connection using parameters taken from a string. Unlike PQsetdbLogin(), the parameter set can be extended without changing the function signature, so use of this routine is encouraged for new application programming. The passed string can be empty to use all default parameters, or it can contain one or more parameter settings separated by whitespace. Each parameter setting is in the form keyword = value. (To write a null value or a value containing spaces, surround it with single quotes, eg, keyword = 'a value'. Single quotes within the value must be written as \'. Spaces around the equal sign are optional.) The currently recognized parameter keywords are:<ItemizedList><ListItem><Para><Acronym>host</Acronym> -- host to connect to.If a non-zero-length string is specified, TCP/IP communication is used.Without a host name, libpq will connect using a local Unix domain socket.</Para></ListItem><ListItem><Para><Acronym>port</Acronym> -- port number to connect to at the server host,or socket filename extension for Unix-domain connections.</Para></ListItem><ListItem><Para><Acronym>dbname</Acronym> -- database name.</Para></ListItem><ListItem><Para><Acronym>user</Acronym> -- user name for authentication.</Para></ListItem><ListItem><Para><Acronym>password</Acronym> -- password used if the backend demands password authentication.</Para></ListItem><ListItem><Para><Acronym>authtype</Acronym> -- authorization type. (No longer used,since the backend now chooses how to authenticate users. libpq stillaccepts and ignores this keyword for backward compatibility.)</Para></ListItem><ListItem><Para><Acronym>options</Acronym> -- trace/debug options to send to backend.</Para></ListItem><ListItem><Para><Acronym>tty</Acronym> -- file or tty for optional debug output from backend.</Para></ListItem></ItemizedList>Like PQsetdbLogin, PQconnectdb uses environment variables or built-indefault values for unspecified options.</Para></ListItem><ListItem><Para><Function>PQconndefaults</Function> Returns the default connection options.<synopsis>PQconninfoOption *PQconndefaults(void)struct PQconninfoOption { char *keyword; /* The keyword of the option */ char *envvar; /* Fallback environment variable name */ char *compiled; /* Fallback compiled in default value */ char *val; /* Option's value */ char *label; /* Label for field in connect dialog */ char *dispchar; /* Character to display for this field in a connect dialog. Values are: "" Display entered value as is "*" Password field - hide value "D" Debug options - don't create a field by default */ int dispsize; /* Field size in characters for dialog */ };</synopsis> Returns the address of the connection options structure. This may be used to determine all possible PQconnectdb options and their current default values. The return value points to an array of PQconninfoOption structs, which ends with an entry having a NULL keyword pointer. Note that the default values ("val" fields) will depend on environment variables and other context. Callers must treat the connection options data as read-only.</Para></ListItem><ListItem><Para><Function>PQfinish</Function> Close the connection to the backend. Also frees memory used by the PGconn object.<synopsis>void PQfinish(PGconn *conn)</synopsis>Note that even if the backend connection attempt fails (asindicated by PQstatus), the application should call PQfinishto free the memory used by the PGconn object.The PGconn pointer should not be used after PQfinish has been called.</Para></ListItem><ListItem><Para><Function>PQreset</Function> Reset the communication port with the backend.<synopsis>void PQreset(PGconn *conn)</synopsis> This function will close the connection to the backend and attempt to reestablish a new connection to the same postmaster, using all the same parameters previously used. This may be useful for error recovery if a working connection is lost.</Para></ListItem></ItemizedList></Para><Para><FileName>libpq</FileName> application programmers should be careful tomaintain the PGconn abstraction. Use the accessor functions below to getat the contents of PGconn. Avoid directly referencing the fields of thePGconn structure because they are subject to change in the future.(Beginning in <ProductName>Postgres</ProductName> release 6.4, thedefinition of struct PGconn is not even provided in libpq-fe.h. If youhave old code that accesses PGconn fields directly, you can keep using itby including libpq-int.h too, but you are encouraged to fix the codesoon.)<ItemizedList><ListItem><Para><Function>PQdb</Function> Returns the database name of the connection.<synopsis>char *PQdb(PGconn *conn)</synopsis>PQdb and the next several functions return the values establishedat connection. These values are fixed for the life of the PGconnobject.</Para></ListItem><ListItem><Para><Function>PQuser</Function> Returns the user name of the connection.<synopsis>char *PQuser(PGconn *conn)</synopsis></Para></ListItem><ListItem><Para><Function>PQpass</Function> Returns the password of the connection.<synopsis>char *PQpass(PGconn *conn)</synopsis></Para></ListItem><ListItem><Para><Function>PQhost</Function> Returns the server host name of the connection.<synopsis>char *PQhost(PGconn *conn)</synopsis></Para></ListItem><ListItem><Para><Function>PQport</Function> Returns the port of the connection.<synopsis>char *PQport(PGconn *conn)</synopsis></Para></ListItem><ListItem><Para><Function>PQtty</Function> Returns the debug tty of the connection.<synopsis>char *PQtty(PGconn *conn)</synopsis></Para></ListItem><ListItem><Para><Function>PQoptions</Function> Returns the backend options used in the connection.<synopsis>char *PQoptions(PGconn *conn)</synopsis></Para></ListItem><ListItem><Para><Function>PQstatus</Function> Returns the status of the connection. The status can be CONNECTION_OK or CONNECTION_BAD.<synopsis>ConnStatusType PQstatus(PGconn *conn)</synopsis></Para><Para>A failed connection attempt is signaled by status CONNECTION_BAD.Ordinarily, an OK status will remain so until PQfinish, but acommunications failure might result in the status changing toCONNECTION_BAD prematurely. In that case the application couldtry to recover by calling PQreset.</Para></ListItem><ListItem><Para><Function>PQerrorMessage</Function> Returns the error message most recently generated by an operation on the connection.<synopsis>char *PQerrorMessage(PGconn* conn);</synopsis></Para><Para>Nearly all libpq functions will set PQerrorMessage if they fail.Note that by libpq convention, a non-empty PQerrorMessage willinclude a trailing newline.</Para></ListItem><ListItem><Para><Function>PQbackendPID</Function> Returns the process ID of the backend server handling this connection.<synopsis>int PQbackendPID(PGconn *conn);</synopsis>The backend PID is useful for debugging purposes and for comparisonto NOTIFY messages (which include the PID of the notifying backend).Note that the PID belongs to a process executing on the databaseserver host, not the local host!</Para></ListItem></ItemizedList></Para></Sect1><Sect1><Title>Query Execution Functions</Title><Para>Once a connection to a database server has been successfullyestablished, the functions described here are used to performSQL queries and commands.<ItemizedList><ListItem><Para><Function>PQexec</Function> Submit a query to <ProductName>Postgres</ProductName> and wait for the result.<synopsis>PGresult *PQexec(PGconn *conn, const char *query);</synopsis> Returns a PGresult pointer 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 query to the backend. If a NULL is returned, it should be treated like a PGRES_FATAL_ERROR result. Use PQerrorMessage to get more information about the error.</Para></ListItem></ItemizedList></Para><Para>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -