first commit for openGauss connector jdbc

This commit is contained in:
lishifu
2020-06-30 14:58:21 +08:00
parent f2f872da1f
commit 8617931d2b
731 changed files with 137912 additions and 73 deletions

View File

@ -0,0 +1,179 @@
---
layout: default_docs
title: Chapter 7. Storing Binary Data
header: Chapter 7. Storing Binary Data
resource: media
previoustitle: Chapter 6. Calling Stored Functions
previous: callproc.html
nexttitle: Chapter 8. JDBC escapes
next: escapes.html
---
PostgreSQL™ provides two distinct ways to store binary data. Binary data can be
stored in a table using the data type BYTEA or by using the Large Object feature
which stores the binary data in a separate table in a special format and refers
to that table by storing a value of type OID in your table.
In order to determine which method is appropriate you need to understand the
limitations of each method. The BYTEA data type is not well suited for storing
very large amounts of binary data. While a column of type BYTEA can hold up to
1 GB of binary data, it would require a huge amount of memory to process such a
large value. The Large Object method for storing binary data is better suited to
storing very large values, but it has its own limitations. Specifically deleting
a row that contains a Large Object reference does not delete the Large Object.
Deleting the Large Object is a separate operation that needs to be performed.
Large Objects also have some security issues since anyone connected to the
database can view and/or modify any Large Object, even if they don't have
permissions to view/update the row containing the Large Object reference.
Version 7.2 was the first release of the JDBC driver that supports the BYTEA
data type. The introduction of this functionality in 7.2 has introduced a change
in behavior as compared to previous releases. Since 7.2, the methods `getBytes()`,
`setBytes()`, `getBinaryStream()`, and `setBinaryStream()` operate on the BYTEA
data type. In 7.1 and earlier, these methods operated on the OID data type
associated with Large Objects. It is possible to revert the driver back to the
old 7.1 behavior by setting the property `compatible` on the `Connection` object
to the value `7.1`. More details on connection properties are available in the
section called [“Connection Parameters”](connect.html#connection-parameters).
To use the BYTEA data type you should simply use the `getBytes()`, `setBytes()`,
`getBinaryStream()`, or `setBinaryStream()` methods.
To use the Large Object functionality you can use either the `LargeObject` class
provided by the PostgreSQL™ JDBC driver, or by using the `getBLOB()` and `setBLOB()`
methods.
### Important
> You must access Large Objects within an SQL transaction block. You can start a
transaction block by calling `setAutoCommit(false)`.
[Example 7.1, “Processing Binary Data in JDBC”](binary-data.html#binary-data-example)
contains some examples on how to process binary data using the PostgreSQL™ JDBC
driver.
<a name="binary-data-example"></a>
***Example 7.1. Processing Binary Data in JDBC***
For example, suppose you have a table containing the file names of images and you
also want to store the image in a BYTEA column:
`CREATE TABLE images (imgname text, img bytea);`
To insert an image, you would use:
`File file = new File("myimage.gif");`
`FileInputStream fis = new FileInputStream(file);`
`PreparedStatement ps = conn.prepareStatement("INSERT INTO images VALUES (?, ?)");`
`ps.setString(1, file.getName());`
`ps.setBinaryStream(2, fis, (int)file.length());`
`ps.executeUpdate();`
`ps.close();`
`fis.close();`
Here, `setBinaryStream()` transfers a set number of bytes from a stream into the
column of type BYTEA. This also could have been done using the `setBytes()` method
if the contents of the image was already in a `byte[]`.
### Note
> The length parameter to `setBinaryStream` must be correct. There is no way to
indicate that the stream is of unknown length. If you are in this situation, you
must read the stream yourself into temporary storage and determine the length.
Now with the correct length you may send the data from temporary storage on to
the driver.
Retrieving an image is even easier. (We use `PreparedStatement` here, but the
`Statement` class can equally be used.)
`PreparedStatement ps = conn.prepareStatement("SELECT img FROM images WHERE imgname = ?");`
`ps.setString(1, "myimage.gif");`
`ResultSet rs = ps.executeQuery();`
`while (rs.next())`
`{`
&nbsp;&nbsp;&nbsp;`byte[] imgBytes = rs.getBytes(1);`
&nbsp;&nbsp;&nbsp;`// use the data in some way here`
`}`
`rs.close();`
`ps.close();`
Here the binary data was retrieved as an `byte[]`. You could have used a
`InputStream` object instead.
Alternatively you could be storing a very large file and want to use the
`LargeObject` API to store the file:
`CREATE TABLE imageslo (imgname text, imgoid oid);`
To insert an image, you would use:
`// All LargeObject API calls must be within a transaction block`
`conn.setAutoCommit(false);``<br />
`// Get the Large Object Manager to perform operations with`
`LargeObjectManager lobj = conn.unwrap(org.postgresql.PGConnection.class).getLargeObjectAPI();`<br />
`// Create a new large object`
`long oid = lobj.createLO(LargeObjectManager.READ | LargeObjectManager.WRITE);`<br />
`// Open the large object for writing`
`LargeObject obj = lobj.open(oid, LargeObjectManager.WRITE);`<br />
`// Now open the file`
`File file = new File("myimage.gif");`
`FileInputStream fis = new FileInputStream(file);`<br />
`// Copy the data from the file to the large object`
`byte buf[] = new byte[2048];`
`int s, tl = 0;`
`while ((s = fis.read(buf, 0, 2048)) > 0)`
`{`
&nbsp;&nbsp;&nbsp;`obj.write(buf, 0, s);`
&nbsp;&nbsp;&nbsp;`tl += s;`
`}`<br />
`// Close the large object`
`obj.close();`<br />
`// Now insert the row into imageslo`
`PreparedStatement ps = conn.prepareStatement("INSERT INTO imageslo VALUES (?, ?)");`
`ps.setString(1, file.getName());`
`ps.setLong(2, oid);`
`ps.executeUpdate();`
`ps.close();`
`fis.close();`<br />
`// Finally, commit the transaction.`
`conn.commit();`
Retrieving the image from the Large Object:
`// All LargeObject API calls must be within a transaction block`
`conn.setAutoCommit(false);`<br />
`// Get the Large Object Manager to perform operations with`
`LargeObjectManager lobj = conn.unwrap(org.postgresql.PGConnection.class).getLargeObjectAPI();`<br />
`PreparedStatement ps = conn.prepareStatement("SELECT imgoid FROM imageslo WHERE imgname = ?");`
`ps.setString(1, "myimage.gif");`
`ResultSet rs = ps.executeQuery();`
`while (rs.next())`
`{`
&nbsp;&nbsp;&nbsp;`// Open the large object for reading`
&nbsp;&nbsp;&nbsp;`long oid = rs.getLong(1);`
&nbsp;&nbsp;&nbsp;`LargeObject obj = lobj.open(oid, LargeObjectManager.READ);`<br />
&nbsp;&nbsp;&nbsp;`// Read the data`
&nbsp;&nbsp;&nbsp;`byte buf[] = new byte[obj.size()];`
&nbsp;&nbsp;&nbsp;`obj.read(buf, 0, obj.size());`
&nbsp;&nbsp;&nbsp;`// Do something with the data read here`<br />
&nbsp;&nbsp;&nbsp;`// Close the object`
&nbsp;&nbsp;&nbsp;`obj.close();`
`}`
`rs.close();`
`ps.close();`<br />
`// Finally, commit the transaction.`
`conn.commit();`

View File

@ -0,0 +1,116 @@
---
layout: default_docs
title: Chapter 6. Calling Stored Functions
header: Chapter 6. Calling Stored Functions
resource: media
previoustitle: Creating and Modifying Database Objects
previous: ddl.html
nexttitle: Chapter 7. Storing Binary Data
next: binary-data.html
---
**Table of Contents**
* [Obtaining a `ResultSet` from a stored function](callproc.html#callproc-resultset)
* [From a Function Returning `SETOF` type](callproc.html#callproc-resultset-setof)
* [From a Function Returning a refcursor](callproc.html#callproc-resultset-refcursor)
<a name="call-function-example"></a>
**Example 6.1. Calling a built in stored function**
This example shows how to call a PostgreSQL™ built in function, `upper`, which
simply converts the supplied string argument to uppercase.
`CallableStatement upperProc = conn.prepareCall("{ ? = call upper( ? ) }");`
`upperProc.registerOutParameter(1, Types.VARCHAR);`
`upperProc.setString(2, "lowercase to uppercase");`
`upperProc.execute();`
`String upperCased = upperProc.getString(1);`
`upperProc.close();`
<a name="callproc-resultset"></a>
# Obtaining a `ResultSet` from a stored function
PostgreSQL's™ stored functions can return results in two different ways. The
function may return either a refcursor value or a `SETOF` some datatype. Depending
on which of these return methods are used determines how the function should be
called.
<a name="callproc-resultset-setof"></a>
## From a Function Returning `SETOF` type
Functions that return data as a set should not be called via the `CallableStatement`
interface, but instead should use the normal `Statement` or `PreparedStatement`
interfaces.
<a name="setof-resultset"></a>
**Example 6.2. Getting `SETOF` type values from a function**
`Statement stmt = conn.createStatement();`
`stmt.execute("CREATE OR REPLACE FUNCTION setoffunc() RETURNS SETOF int AS "`
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`+ "' SELECT 1 UNION SELECT 2;' LANGUAGE sql");`
`ResultSet rs = stmt.executeQuery("SELECT * FROM setoffunc()");`
`while (rs.next())`
`{`
&nbsp;&nbsp;&nbsp;`// do something`
`}`
`rs.close();`
`stmt.close();`
<a name="callproc-resultset-refcursor"></a>
## From a Function Returning a refcursor
When calling a function that returns a refcursor you must cast the return type of
`getObject` to a `ResultSet`
### Note
> One notable limitation of the current support for a `ResultSet` created from
a refcursor is that even though it is a cursor backed `ResultSet`, all data will
be retrieved and cached on the client. The `Statement` fetch size parameter
described in the section called [“Getting results based on a cursor”](query.html#query-with-cursor)
is ignored. This limitation is a deficiency of the JDBC driver, not the server,
and it is technically possible to remove it, we just haven't found the time.
<a name="get-refcursor-from-function-call"></a>
**Example 6.3. Getting refcursor Value From a Function**
`// Setup function to call.`
`Statement stmt = conn.createStatement();`
`stmt.execute("CREATE OR REPLACE FUNCTION refcursorfunc() RETURNS refcursor AS '"`
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`+ " DECLARE "`
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`+ " mycurs refcursor; "`
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`+ " BEGIN "`
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`+ " OPEN mycurs FOR SELECT 1 UNION SELECT 2; "`
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`+ " RETURN mycurs; "`
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`+ " END;' language plpgsql");`
`stmt.close();`<br />
`// We must be inside a transaction for cursors to work.`
`conn.setAutoCommit(false);`<br />
`// Procedure call.`
`CallableStatement proc = conn.prepareCall("{ ? = call refcursorfunc() }");`
`proc.registerOutParameter(1, Types.OTHER);`
`proc.execute();`
`ResultSet results = (ResultSet) proc.getObject(1);`
`while (results.next())`
`{`
&nbsp;&nbsp;&nbsp;`// do something with the results.`
`}`
`results.close();`
`proc.close();`
It is also possible to treat the refcursor return value as a cursor name directly.
To do this, use the `getString` of `ResultSet`. With the underlying cursor name,
you are free to directly use cursor commands on it, such as `FETCH` and `MOVE`.
<a name="refcursor-string-example"></a>
**Example 6.4. Treating refcursor as a cursor name**
`conn.setAutoCommit(false);`
`CallableStatement proc = conn.prepareCall("{ ? = call refcursorfunc() }");`
`proc.registerOutParameter(1, Types.OTHER);`
`proc.execute();`
`String cursorName = proc.getString(1);`
`proc.close();`

View File

@ -0,0 +1,26 @@
---
layout: default_docs
title: Setting up the Class Path
header: Chapter 2. Setting up the JDBC Driver
resource: media
previoustitle: Chapter 2. Setting up the JDBC Driver
previous: setup.html
nexttitle: Preparing the Database Server for JDBC
next: prepare.html
---
To use the driver, the JAR archive named `postgresql.jar` if you built from source,
otherwise it will likely be (named with the following convention: `postgresql-*[server version]*.*[build number]*.jdbc*[JDBC version]*.jar`,
for example `postgresql-8.0-310.jdbc3.jar`) needs to be included in the class path,
either by putting it in the `CLASSPATH` environment variable, or by using flags on
the **java** command line.
For instance, assume we have an application that uses the JDBC driver to access
a database, and that application is installed as `/usr/local/lib/myapp.jar`. The
PostgreSQL™ JDBC driver installed as `/usr/local/pgsql/share/java/postgresql.jar`.
To run the application, we would use:
*export CLASSPATH=/usr/local/lib/myapp.jar:/usr/local/pgsql/share/java/postgresql.jar:*.
*java MyApp*
Loading the driver from within the application is covered in [Chapter 3, Initializing the Driver](use.html).

View File

@ -0,0 +1,234 @@
---
layout: default_docs
title: Connecting to the Database
header: Chapter 3. Initializing the Driver
resource: media
previoustitle: Loading the Driver
previous: load.html
nexttitle: Chapter 4. Using SSL
next: ssl.html
---
With JDBC, a database is represented by a URL (Uniform Resource Locator). With
PostgreSQL™, this takes one of the following forms:
* jdbc:postgresql:*`database`*
* jdbc:postgresql:/
* jdbc:postgresql://*`host/database`*
* jdbc:postgresql://*`host/`*
* jdbc:postgresql://*`host:port/database`*
* jdbc:postgresql://*`host:port/`*
The parameters have the following meanings:
* *`host`*
The host name of the server. Defaults to `localhost`. To specify an IPv6
address your must enclose the `host` parameter with square brackets, for
example:
jdbc:postgresql://[::1]:5740/accounting
* *`port`*
The port number the server is listening on. Defaults to the PostgreSQL™
standard port number (5432).
* *`database`*
The database name. The default is to connect to a database with the same name
as the user name.
To connect, you need to get a `Connection` instance from JDBC. To do this, you use
the `DriverManager.getConnection()` method:
`Connection db = DriverManager.getConnection(url, username, password)`;
<a name="connection-parameters"></a>
## Connection Parameters
In addition to the standard connection parameters the driver supports a number
of additional properties which can be used to specify additional driver behaviour
specific to PostgreSQL™. These properties may be specified in either the connection
URL or an additional `Properties` object parameter to `DriverManager.getConnection`.
The following examples illustrate the use of both methods to establish a SSL
connection.
`String url = "jdbc:postgresql://localhost/test";`
`Properties props = new Properties();`
`props.setProperty("user","fred");`
`props.setProperty("password","secret");`
`props.setProperty("ssl","true");`
`Connection conn = DriverManager.getConnection(url, props);`
`String url = "jdbc:postgresql://localhost/test?user=fred&password=secret&ssl=true";`
`Connection conn = DriverManager.getConnection(url);`
* `user = String`
The database user on whose behalf the connection is being made.
* `password = String`
The database user's password.
* `ssl`
Connect using SSL. The driver must have been compiled with SSL support.
This property does not need a value associated with it. The mere presence
of it specifies a SSL connection. However, for compatibility with future
versions, the value "true" is preferred. For more information see [Chapter
4, *Using SSL*](ssl.html).
* `sslfactory = String`
The provided value is a class name to use as the `SSLSocketFactory` when
establishing a SSL connection. For more information see the section
called [“Custom SSLSocketFactory”](ssl-factory.html).
* `sslfactoryarg = String`
This value is an optional argument to the constructor of the sslfactory
class provided above. For more information see the section called [“Custom SSLSocketFactory”](ssl-factory.html).
* `compatible = String`
Act like an older version of the driver to retain compatibility with older
applications. At the moment this controls two driver behaviours: the
handling of binary data fields, and the handling of parameters set via
`setString()`.
Older versions of the driver used this property to also control the
protocol used to connect to the backend. This is now controlled by the
`protocolVersion` property.
Information on binary data handling is detailed in [Chapter 7, Storing Binary Data](binary-data.html).
To force the use of Large Objects set the compatible property to 7.1.
When `compatible` is set to 7.4 or below, the default for the `stringtype`
parameter is changed to `unspecified`.
* `sendBufferSize = int`
Sets SO_SNDBUF on the connection stream
* `recvBufferSize = int`
Sets SO_RCVBUF on the connection stream
* `protocolVersion = String`
The driver supports both the V2 and V3 frontend/backend protocols. The
V3 protocol was introduced in 7.4 and the driver will by default try to
connect using the V3 protocol, if that fails it will fall back to the V2
protocol. If the protocolVersion property is specified, the driver will
try only the specified protocol (which should be either "2" or "3").
Setting protocolVersion to "2" may be used to avoid the failed attempt
to use the V3 protocol when connecting to a version 7.3 or earlier server,
or to force the driver to use the V2 protocol despite connecting to a 7.4
or greater server.
* `loglevel = int`
Set the amount of logging information printed to the DriverManager's
current value for LogStream or LogWriter. It currently supports values
of `org.postgresql.Driver.DEBUG` (2) and `org.postgresql.Driver.INFO` (1).
`INFO` will log very little information while `DEBUG` will produce significant
detail. This property is only really useful if you are a developer or
are having problems with the driver.
* `charSet = String`
The character set to use for data sent to the database or received from
the database. This property is only relevant for server versions less
than or equal to 7.2. The 7.3 release was the first with multibyte support
compiled by default and the driver uses its character set translation
facilities instead of trying to do it itself.
* `allowEncodingChanges = boolean`
When using the V3 protocol the driver monitors changes in certain server
configuration parameters that should not be touched by end users. The
`client_encoding` setting is set by the driver and should not be altered.
If the driver detects a change it will abort the connection. There is
one legitimate exception to this behaviour though, using the `COPY` command
on a file residing on the server's filesystem. The only means of specifying
the encoding of this file is by altering the `client_encoding` setting.
The JDBC team considers this a failing of the `COPY` command and hopes to
provide an alternate means of specifying the encoding in the future, but
for now there is this URL parameter. Enable this only if you need to
override the client encoding when doing a copy.
* `logUnclosedConnections = boolean`
Clients may leak `Connection` objects by failing to call its `close()`
method. Eventually these objects will be garbage collected and the
`finalize()` method will be called which will close the `Connection` if
caller has neglected to do this himself. The usage of a finalizer is just
a stopgap solution. To help developers detect and correct the source of
these leaks the `logUnclosedConnections` URL parameter has been added.
It captures a stacktrace at each `Connection` opening and if the `finalize()`
method is reached without having been closed the stacktrace is printed
to the log.
* `prepareThreshold = int`
Determine the number of `PreparedStatement` executions required before
switching over to use server side prepared statements. The default is
five, meaning start using server side prepared statements on the fifth
execution of the same `PreparedStatement` object. More information on
server side prepared statements is available in the section called
[“Server Prepared Statements”](server-prepare.html).
* `loginTimeout = int`
Specify how long to wait for establishment of a database connection. The
timeout is specified in seconds.
* `socketTimeout = int`
The timeout value used for socket read operations. If reading from the
server takes longer than this value, the connection is closed. This can
be used as both a brute force global query timeout and a method of
detecting network problems. The timeout is specified in seconds and a
value of zero means that it is disabled.
* `tcpKeepAlive = boolean`
Enable or disable TCP keep-alive probe. The default is `false`.
* `unknownLength = int`
Certain postgresql types such as `TEXT` do not have a well defined length.
When returning meta-data about these types through functions like
`ResultSetMetaData.getColumnDisplaySize` and `ResultSetMetaData.getPrecision`
we must provide a value and various client tools have different ideas
about what they would like to see. This parameter specifies the length
to return for types of unknown length.
* `stringtype = String`
Specify the type to use when binding `PreparedStatement` parameters set
via `setString()`. If `stringtype` is set to `VARCHAR` (the default), such
parameters will be sent to the server as varchar parameters. If `stringtype`
is set to `unspecified`, parameters will be sent to the server as untyped
values, and the server will attempt to infer an appropriate type. This
is useful if you have an existing application that uses `setString()` to
set parameters that are actually some other type, such as integers, and
you are unable to change the application to use an appropriate method
such as `setInt()`.
* `kerberosServerName = String`
The Kerberos service name to use when authenticating with GSSAPI. This
is equivalent to libpq's PGKRBSRVNAME environment variable and defaults
to "postgres".
* `jaasApplicationName = String`
Specifies the name of the JAAS system or application login configuration.
* `ApplicationName = String`
Specifies the name of the application that is using the connection.
This allows a database administrator to see what applications are
connected to the server and what resources they are using through views like pg_stat_activity.

View File

@ -0,0 +1,44 @@
---
layout: default_docs
title: Chapter 11. Connection Pools and Data Sources
header: Chapter 11. Connection Pools and Data Sources
resource: media
previoustitle: Chapter 10. Using the Driver in a Multithreaded or a Servlet Environment
previous: thread.html
nexttitle: Application Servers ConnectionPoolDataSource
next: ds-cpds.html
---
**Table of Contents**
* [Overview](datasource.html#ds-intro)
* [Application Servers: `ConnectionPoolDataSource`](ds-cpds.html)
* [Applications: `DataSource`](ds-ds.html)
* [Tomcat setup](tomcat.html)
* [Data Sources and JNDI](jndi.html)
JDBC 2 introduced standard connection pooling features in an add-on API known as
the JDBC 2.0 Optional Package (also known as the JDBC 2.0 Standard Extension).
These features have since been included in the core JDBC 3 API.
<a name="ds-intro"></a>
# Overview
The JDBC API provides a client and a server interface for connection pooling.
The client interface is `javax.sql.DataSource`, which is what application code
will typically use to acquire a pooled database connection. The server interface
is `javax.sql.ConnectionPoolDataSource`, which is how most application servers
will interface with the PostgreSQL™ JDBC driver.
In an application server environment, the application server configuration will
typically refer to the PostgreSQL™ `ConnectionPoolDataSource` implementation,
while the application component code will typically acquire a `DataSource`
implementation provided by the application server (not by PostgreSQL™).
For an environment without an application server, PostgreSQL™ provides two
implementations of `DataSource` which an application can use directly. One
implementation performs connection pooling, while the other simply provides
access to database connections through the `DataSource` interface without any
pooling. Again, these implementations should not be used in an application server
environment unless the application server does not support the `ConnectionPoolDataSource`
interface.

View File

@ -0,0 +1,24 @@
---
layout: default_docs
title: Creating and Modifying Database Objects
header: Chapter 5. Issuing a Query and Processing the Result
resource: media
previoustitle: Performing Updates
previous: update.html
nexttitle: Chapter 6. Calling Stored Functions
next: callproc.html
---
To create, modify or drop a database object like a table or view you use the
`execute()` method. This method is similar to the method `executeQuery()`, but
it doesn't return a result. [Example 5.4, “Dropping a Table in JDBC](ddl.html#drop-table-example)
illustrates the usage.
<a name="drop-table-example"></a>
**Example 5.4. Dropping a Table in JDBC**
This example will drop a table.
`Statement st = conn.createStatement();`
`st.execute("DROP TABLE mytable");`
`st.close();`

View File

@ -0,0 +1,93 @@
---
layout: default_docs
title: Application Servers ConnectionPoolDataSource
header: Chapter 11. Connection Pools and Data Sources
resource: media
previoustitle: Chapter 11. Connection Pools and Data Sources
previous: datasource.html
nexttitle: Applications DataSource
next: ds-ds.html
---
PostgreSQL™ includes one implementation of `ConnectionPoolDataSource` named
`org.postgresql.ds.PGConnectionPoolDataSource`.
JDBC requires that a `ConnectionPoolDataSource` be configured via JavaBean
properties, shown in [Table 11.1, “`ConnectionPoolDataSource` Configuration Properties”](ds-cpds.html#ds-cpds-props),
so there are get and set methods for each of these properties.
<a name="ds-cpds-props"></a>
**Table 11.1. `ConnectionPoolDataSource` Configuration Properties**
<table summary="ConnectionPoolDataSource Configuration Properties"
border="1">
<tr>
<th>Property</th>
<th>Type</th>
<th>Description</th>
</tr>
<tbody>
<tr>
<td>serverName</td>
<td>STRING</td>
<td>PostgreSQL™ database server
host name</td>
</tr>
<tr>
<td>databaseName</td>
<td>STRING</td>
<td>PostgreSQL™ database name</td>
</tr>
<tr>
<td>portNumber</td>
<td>INT</td>
<td> TCP port which the PostgreSQL™
database server is listening on (or 0 to use the default port) </td>
</tr>
<tr>
<td>user</td>
<td>STRING</td>
<td>User used to make database connections</td>
</tr>
<tr>
<td>password</td>
<td>STRING</td>
<td>Password used to make database connections</td>
</tr>
<tr>
<td>ssl</td>
<td>BOOLEAN</td>
<td> If `true`, use SSL encrypted
connections (default `false`) </td>
</tr>
<tr>
<td>sslfactory</td>
<td>STRING</td>
<td> Custom `javax.net.ssl.SSLSocketFactory`
class name (see the section called [“Custom
SSLSocketFactory”](ssl-factory.html)) </td>
</tr>
<tr>
<td>defaultAutoCommit</td>
<td>BOOLEAN</td>
<td> Whether connections should have autocommit enabled or
disabled when they are supplied to the caller. The default is `false`, to disable autocommit. </td>
</tr>
</tbody>
</table>
Many application servers use a properties-style syntax to configure these
properties, so it would not be unusual to enter properties as a block of text.
If the application server provides a single area to enter all the properties,
they might be listed like this:
`serverName=localhost`
`databaseName=test`
`user=testuser`
`password=testpassword`
Or, if semicolons are used as separators instead of newlines, it could look like
this:
`serverName=localhost;databaseName=test;user=testuser;password=testpassword`

View File

@ -0,0 +1,178 @@
---
layout: default_docs
title: Applications DataSource
header: Chapter 11. Connection Pools and Data Sources
resource: media
previoustitle: Application Servers ConnectionPoolDataSource
previous: ds-cpds.html
nexttitle: Tomcat setup
next: tomcat.html
---
PostgreSQL™ includes two implementations of `DataSource`, as shown in [Table 11.2, “`DataSource` Implementations”](ds-ds.html#ds-ds-imp).
One that does pooling and the other that does not. The pooling implementation
does not actually close connections when the client calls the `close` method,
but instead returns the connections to a pool of available connections for other
clients to use. This avoids any overhead of repeatedly opening and closing
connections, and allows a large number of clients to share a small number of
database connections.
The pooling data-source implementation provided here is not the most feature-rich
in the world. Among other things, connections are never closed until the pool
itself is closed; there is no way to shrink the pool. As well, connections
requested for users other than the default configured user are not pooled. Its
error handling sometimes cannot remove a broken connection from the pool. In
general it is not recommended to use the PostgreSQL™ provided connection pool.
Check your application server or check out the excellent [jakarta commons DBCP](http://jakarta.apache.org/commons/dbcp/)
project.
<a name="ds-ds-imp"></a>
**Table 11.2. `DataSource` Implementations**
<table summary="DataSource Implementations" border="1">
<tr>
<th>Pooling</th>
<th>Implementation Class</th>
</tr>
<tbody>
<tr>
<td>No</td>
<td>`org.postgresql.ds.PGSimpleDataSource</td>
</tr>
<tr>
<td>Yes</td>
<td>`org.postgresql.ds.PGPoolingDataSource</td>
</tr>
</tbody>
</table>
Both implementations use the same configuration scheme. JDBC requires that a
`DataSource` be configured via JavaBean properties, shown in [Table 11.3, “`DataSource` Configuration Properties”](ds-ds.html#ds-ds-props),
so there are get and set methods for each of these properties.
<a name="ds-ds-props"></a>
**Table 11.3. `DataSource` Configuration Properties**
<table summary="DataSource Configuration Properties" border="1">
<tr>
<th>Property</th>
<th>Type</th>
<th>Description</th>
</tr>
<tbody>
<tr>
<td>serverName</td>
<td>STRING</td>
<td>PostgreSQL™ database server host name</td>
</tr>
<tr>
<td>databaseName</td>
<td>STRING</td>
<td>PostgreSQL™ database name</td>
</tr>
<tr>
<td>portNumber</td>
<td>INT</td>
<td>TCP port which the PostgreSQL™
database server is listening on (or 0 to use the default port)</td>
</tr>
<tr>
<td>user</td>
<td>STRING</td>
<td>User used to make database connections</td>
</tr>
<tr>
<td>password</td>
<td>STRING</td>
<td>Password used to make database connections</td>
</tr>
<tr>
<td>ssl</td>
<td>BOOLEAN</td>
<td> If true, use SSL encrypted
connections (default false) </td>
</tr>
<tr>
<td>sslfactory</td>
<td>STRING</td>
<td> Custom javax.net.ssl.SSLSocketFactory
class name (see the section called [“Custom
SSLSocketFactory”](ssl-factory.html))</td>
</tr>
</tbody>
</table>
The pooling implementation requires some additional configuration properties,
which are shown in [Table 11.4, “Additional Pooling `DataSource` Configuration Properties](ds-ds.html#ds-ds-xprops).
<a name="ds-ds-xprops"></a>
**Table 11.4. Additional Pooling `DataSource` Configuration Properties**
<table summary="Additional Pooling DataSource Configuration Properties" border="1">
<tr>
<th>Property</th>
<th>Type</th>
<th>Description</th>
</tr>
<tbody>
<tr>
<td>dataSourceName</td>
<td>STRING</td>
<td>Every pooling DataSource must
have a unique name.</td>
</tr>
<tr>
<td>initialConnections</td>
<td>INT</td>
<td>The number of database connections to be created when the
pool is initialized.</td>
</tr>
<tr>
<td>maxConnections</td>
<td>INT</td>
<td>The maximum number of open database connections to allow.
When more connections are requested, the caller will hang until a
connection is returned to the pool.</td>
</tr>
</tbody>
</table>
[Example 11.1, “`DataSource` Code Example”](ds-ds.html#ds-example) shows an example
of typical application code using a pooling `DataSource`.
<a name="ds-example"></a>
**Example 11.1. `DataSource` Code Example**
Code to initialize a pooling `DataSource` might look like this:
`PGPoolingDataSource source = new PGPoolingDataSource();`
`source.setDataSourceName("A Data Source");`
`source.setServerName("localhost");`
`source.setDatabaseName("test");`
`source.setUser("testuser");`
`source.setPassword("testpassword");`
`source.setMaxConnections(10);`
Then code to use a connection from the pool might look like this. Note that it
is critical that the connections are eventually closed. Else the pool will
“leak” connections and will eventually lock all the clients out.
<pre><code>
Connection conn = null;
try
{
conn = source.getConnection();
// use connection
}
catch (SQLException e)
{
// log error
}
finally
{
if (con != null)
{
try { conn.close(); } catch (SQLException e) {}
}
}
</code></pre>

View File

@ -0,0 +1,480 @@
---
layout: default_docs
title: Escaped scalar functions
header: Chapter 8. JDBC escapes
resource: media
previoustitle: Date-time escapes
previous: escapes-datetime.html
nexttitle: Chapter 9. PostgreSQL™ Extensions to the JDBC API
next: ext.html
---
The JDBC specification defines functions with an escape call syntax : `{fn function_name(arguments)}`.
The following tables show which functions are supported by the PostgresSQL™ driver.
The driver supports the nesting and the mixing of escaped functions and escaped
values. The appendix C of the JDBC specification describes the functions.
Some functions in the following tables are translated but not reported as supported
because they are duplicating or changing their order of the arguments. While this
is harmless for literal values or columns, it will cause problems when using
prepared statements. For example "`{fn right(?,?)}`" will be translated to "`substring(? from (length(?)+1-?))`".
As you can see the translated SQL requires more parameters than before the
translation but the driver will not automatically handle this.
<a name="escape-numeric-functions-table"></a>
**Table 8.1. Supported escaped numeric functions**
<table summary="Supported escaped numeric functions" border="1">
<tr>
<th>function</th>
<th>reported as supported</th>
<th>translation</th>
<th>comments</th>
</tr>
<tbody>
<tr>
<td>abs(arg1)</td>
<td>yes</td>
<td>abs(arg1)</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>acos(arg1)</td>
<td>yes</td>
<td>acos(arg1)</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>asin(arg1)</td>
<td>yes</td>
<td>asin(arg1)</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>atan(arg1)</td>
<td>yes</td>
<td>atan(arg1)</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>atan2(arg1,arg2)</td>
<td>yes</td>
<td>atan2(arg1,arg2)</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>ceiling(arg1)</td>
<td>yes</td>
<td>ceil(arg1)</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>cos(arg1)</td>
<td>yes</td>
<td>cos(arg1)</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>cot(arg1)</td>
<td>yes</td>
<td>cot(arg1)</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>degrees(arg1)</td>
<td>yes</td>
<td>degrees(arg1)</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>exp(arg1)</td>
<td>yes</td>
<td>exp(arg1)</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>floor(arg1)</td>
<td>yes</td>
<td>floor(arg1)</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>log(arg1)</td>
<td>yes</td>
<td>ln(arg1)</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>log10(arg1)</td>
<td>yes</td>
<td>log(arg1)</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>mod(arg1,arg2)</td>
<td>yes</td>
<td>mod(arg1,arg2)</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>pi(arg1)</td>
<td>yes</td>
<td>pi(arg1)</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>power(arg1,arg2)</td>
<td>yes</td>
<td>pow(arg1,arg2)</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>radians(arg1)</td>
<td>yes</td>
<td>radians(arg1)</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>rand()</td>
<td>yes</td>
<td>random()</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>rand(arg1)</td>
<td>yes</td>
<td>setseed(arg1)*0+random()</td>
<td>The seed is initialized with the given argument and a new randow value is returned.</td>
</tr>
<tr>
<td>round(arg1,arg2)</td>
<td>yes</td>
<td>round(arg1,arg2)</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>sign(arg1)</td>
<td>yes</td>
<td>sign(arg1)</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>sin(arg1)</td>
<td>yes</td>
<td>sin(arg1)</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>sqrt(arg1)</td>
<td>yes</td>
<td>sqrt(arg1)</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>tan(arg1)</td>
<td>yes</td>
<td>tan(arg1)</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>truncate(arg1,arg2)</td>
<td>yes</td>
<td>trunc(arg1,arg2)</td>
<td>&nbsp;</td>
</tr>
</tbody>
</table>
<a name="escape-string-functions-table"></a>
**Table 8.2. Supported escaped string functions**
<table summary="Supported escaped string functions" border="1">
<tr>
<th>function</th>
<th>reported as supported</th>
<th>translation</th>
<th>comments</th>
</tr>
<tbody>
<tr>
<td>ascii(arg1)</td>
<td>yes</td>
<td>ascii(arg1)</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>char(arg1)</td>
<td>yes</td>
<td>chr(arg1)</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>concat(arg1,arg2...)</td>
<td>yes</td>
<td>(arg1||arg2...)</td>
<td>The JDBC specification
only require the two arguments version, but supporting more arguments
was so easy...</td>
</tr>
<tr>
<td>insert(arg1,arg2,arg3,arg4)</td>
<td>no</td>
<td>overlay(arg1 placing arg4 from arg2 for arg3)</td>
<td>This function is not reported as supported since it changes
the order of the arguments which can be a problem (for prepared
statements by example).</td>
</tr>
<tr>
<td>lcase(arg1)</td>
<td>yes</td>
<td>lower(arg1)</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>left(arg1,arg2)</td>
<td>yes</td>
<td>substring(arg1 for arg2)</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>length(arg1)</td>
<td>yes</td>
<td>length(trim(trailing from arg1))</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>locate(arg1,arg2)</td>
<td>no</td>
<td>position(arg1 in arg2)</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>locate(arg1,arg2,arg3)</td>
<td>no</td>
<td>(arg2*sign(position(arg1 in substring(arg2 from
arg3)+position(arg1 in substring(arg2 from arg3))</td>
<td>Not reported as supported since the three arguments version
duplicate and change the order of the arguments.</td>
</tr>
<tr>
<td>ltrim(arg1)</td>
<td>yes</td>
<td>trim(leading from arg1)</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>repeat(arg1,arg2)</td>
<td>yes</td>
<td>repeat(arg1,arg2)</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>replace(arg1,arg2,arg3)</td>
<td>yes</td>
<td>replace(arg1,arg2,arg3)</td>
<td>Only reported as supported by 7.3 and above servers.</td>
</tr>
<tr>
<td>right(arg1,arg2)</td>
<td>no</td>
<td>substring(arg1 from (length(arg1)+1-arg2))</td>
<td>Not reported as supported since arg2 is duplicated.</td>
</tr>
<tr>
<td>rtrim(arg1)</td>
<td>yes</td>
<td>trim(trailing from arg1)</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>space(arg1)</td>
<td>yes</td>
<td>repeat(' ',arg1)</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>substring(arg1,arg2)</td>
<td>yes</td>
<td>substr(arg1,arg2)</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>substring(arg1,arg2,arg3)</td>
<td>yes</td>
<td>substr(arg1,arg2,arg3)</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>ucase(arg1)</td>
<td>yes</td>
<td>upper(arg1)</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>soundex(arg1)</td>
<td>no</td>
<td>soundex(arg1)</td>
<td>Not reported as supported since it requires the fuzzystrmatch
contrib module.</td>
</tr>
<tr>
<td>difference(arg1,arg2)</td>
<td>no</td>
<td>difference(arg1,arg2)</td>
<td>Not reported as supported since it requires the fuzzystrmatch
contrib module.</td>
</tr>
</tbody>
</table>
<a name="escape-datetime-functions-table"></a>
**Table 8.3. Supported escaped date/time functions**
<table summary="Supported escaped date/time functions" border="1">
<tr>
<th>function</th>
<th>reported as supported</th>
<th>translation</th>
<th>comments</th>
</tr>
<tbody>
<tr>
<td>curdate()</td>
<td>yes</td>
<td>current_date</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>curtime()</td>
<td>yes</td>
<td>current_time</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>dayname(arg1)</td>
<td>yes</td>
<td>to_char(arg1,'Day')</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>dayofmonth(arg1)</td>
<td>yes</td>
<td>extract(day from arg1)</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>dayofweek(arg1)</td>
<td>yes</td>
<td>extract(dow from arg1)+1</td>
<td>We must add 1 to be in the expected 1-7 range.</td>
</tr>
<tr>
<td>dayofyear(arg1)</td>
<td>yes</td>
<td>extract(doy from arg1)</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>hour(arg1)</td>
<td>yes</td>
<td>extract(hour from arg1)</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>minute(arg1)</td>
<td>yes</td>
<td>extract(minute from arg1)</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>month(arg1)</td>
<td>yes</td>
<td>extract(month from arg1)</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>monthname(arg1)</td>
<td>yes</td>
<td>to_char(arg1,'Month')</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>now()</td>
<td>yes</td>
<td>now()</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>quarter(arg1)</td>
<td>yes</td>
<td>extract(quarter from arg1)</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>second(arg1)</td>
<td>yes</td>
<td>extract(second from arg1)</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>week(arg1)</td>
<td>yes</td>
<td>extract(week from arg1)</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>year(arg1)</td>
<td>yes</td>
<td>extract(year from arg1)</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>timestampadd(argIntervalType,argCount,argTimeStamp)</td>
<td>yes</td>
<td>('(interval according to argIntervalType and
argCount)'+argTimeStamp)</td>
<td>an argIntervalType value of SQL_TSI_FRAC_SECOND
is not implemented since backend does not support it</td>
</tr>
<tr>
<td>timestampdiff(argIntervalType,argTimeStamp1,argTimeStamp2)</td>
<td>not</td>
<td>extract((interval according to argIntervalType) from
argTimeStamp2-argTimeStamp1 )</td>
<td>only an argIntervalType value of SQL_TSI_FRAC_SECOND, SQL_TSI_FRAC_MINUTE, SQL_TSI_FRAC_HOUR
or SQL_TSI_FRAC_DAY is supported </td>
</tr>
</tbody>
</table>
<a name="escape-misc-functions-table"></a>
**Table 8.4. Supported escaped misc functions**
<table summary="Supported escaped misc functions" border="1">
<tr>
<th>function</th>
<th>reported as supported</th>
<th>translation</th>
<th>comments</th>
</tr>
<tbody>
<tr>
<td>database()</td>
<td>yes</td>
<td>current_database()</td>
<td>Only reported as supported by 7.3 and above servers.</td>
</tr>
<tr>
<td>ifnull(arg1,arg2)</td>
<td>yes</td>
<td>coalesce(arg1,arg2)</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>user()</td>
<td>yes</td>
<td>user</td>
<td>&nbsp;</td>
</tr>
</tbody>
</table>

View File

@ -0,0 +1,23 @@
---
layout: default_docs
title: Date-time escapes
header: Chapter 8. JDBC escapes
resource: media
previoustitle: Escape for outer joins
previous: outer-joins-escape.html
nexttitle: Escaped scalar functions
next: escaped-functions.html
---
The JDBC specification defines escapes for specifying date, time and timestamp
values which are supported by the driver.
> date
>> `{d 'yyyy-mm-dd'}` which is translated to `DATE 'yyyy-mm-dd'`
> time
>> `{t 'hh:mm:ss'}` which is translated to `TIME 'hh:mm:ss'`
> timestamp
>> `{ts 'yyyy-mm-dd hh:mm:ss.f...'}` which is translated to `TIMESTAMP 'yyyy-mm-dd hh:mm:ss.f'`<br /><br />
>> The fractional seconds (.f...) portion of the TIMESTAMP can be omitted.

View File

@ -0,0 +1,57 @@
---
layout: default_docs
title: Chapter 8. JDBC escapes
header: Chapter 8. JDBC escapes
resource: media
previoustitle: Chapter 7. Storing Binary Data
previous: binary-data.html
nexttitle: Escape for outer joins
next: outer-joins-escape.html
---
**Table of Contents**
* [Escape for like escape character](escapes.html#like-escape)
* [Escape for outer joins](outer-joins-escape.html)
* [Date-time escapes](escapes-datetime.html)
* [Escaped scalar functions](escaped-functions.html)
The JDBC specification (like the ODBC specification) acknowledges the fact that
some vendor specific SQL may be required for certain RDBMS features. To aid
developers in writing portable JDBC applications across multiple database products,
a special escape syntax is used to specify the generic commands the developer
wants to be run. The JDBC driver translates these escape sequences into native
syntax for its specific database. For more information consult the section 4.1.5
from the [JDBC Technology Guide](http://java.sun.com/j2se/1.4.2/docs/guide/jdbc/getstart/statement.html#999472)
(bundled with the Oracle™ JRE documentation) and the section 13.4 from the
[JDBC 3.0 specification](http://java.sun.com/products/jdbc/download.html#corespec30).
The parsing of the sql statements for these escapes can be disabled using
`Statement.setEscapeProcessing(false)`.
`Connection.nativeSQL(String sql)` provides another way to have escapes processed.
It translates the given SQL to a SQL suitable for the PostgreSQL™ backend.
<a name="escape-use-example"></a>
**Example 8.1. Using jdbc escapes**
To use the JDBC escapes, you simply write your SQL replacing date/time literal
values, outer join and functions by the JDBC escape syntax. For example :
`ResultSet rs = st.executeQuery("SELECT {fn week({d '2005-01-24'})}");`
is the portable version for
`ResultSet rs = st.executeQuery("SELECT extract(week from DATE '2005-01-24')");`
<a name="like-escape"></a>
# Escape for like escape character
You can specify which escape character to use in strings comparison (with `LIKE`)
to protect wildcards characters ('%' and '_') by adding the following escape :
`{escape 'escape-character'}`. The driver supports this only at the end of the
comparison expression.
For example, you can compare string values using '|' as escape character to protect '_' :
`rs = stmt.executeQuery("select str2 from comparisontest where str1 like '|_abcd' {escape '|'} ");`

View File

@ -0,0 +1,36 @@
---
layout: default_docs
title: Chapter 9. PostgreSQL™ Extensions to the JDBC API
header: Chapter 9. PostgreSQL™ Extensions to the JDBC API
resource: media
previoustitle: Escaped scalar functions
previous: escaped-functions.html
nexttitle: Geometric Data Types
next: geometric.html
---
**Table of Contents**
* [Accessing the Extensions](ext.html#extensions)
* [Geometric Data Types](geometric.html)
* [Large Objects](largeobjects.html)
* [Listen / Notify](listennotify.html)
* [Server Prepared Statements](server-prepare.html)
PostgreSQL™ is an extensible database system. You can add your own functions to
the server, which can then be called from queries, or even add your own data types.
As these are facilities unique to PostgreSQL™, we support them from Java, with a
set of extension APIs. Some features within the core of the standard driver
actually use these extensions to implement Large Objects, etc.
<a name="extensions"></a>
# Accessing the Extensions
To access some of the extensions, you need to use some extra methods in the
`org.postgresql.PGConnection` class. In this case, you would need to case the
return value of `Driver.getConnection()`. For example:
`Connection db = Driver.getConnection(url, username, password);`
`// ...`
`// later on`
`Fastpath fp = db.unwrap(org.postgresql.PGConnection.class).getFastpathAPI();`

View File

@ -0,0 +1,68 @@
---
layout: default_docs
title: Geometric Data Types
header: Chapter 9. PostgreSQL™ Extensions to the JDBC API
resource: media
previoustitle: Chapter 9. PostgreSQL™ Extensions to the JDBC API
previous: ext.html
nexttitle: Large Objects
next: largeobjects.html
---
PostgreSQL™ has a set of data types that can store geometric features into a
table. These include single points, lines, and polygons. We support these types
in Java with the org.postgresql.geometric package. Please consult the Javadoc
for the details of available classes and features metioned in [Chapter 12, *Further Reading*](reading.html).
<a name="geometric-circle-example"></a>
**Example 9.1. Using the CIRCLE datatype JDBC**
import java.sql.*;
import org.postgresql.geometric.PGpoint;
import org.postgresql.geometric.PGcircle;
public class GeometricTest {
public static void main(String args[]) throws Exception {
Class.forName("org.postgresql.Driver");
String url = "jdbc:postgresql://localhost:5432/test";
Connection conn = DriverManager.getConnection(url,"test","");
Statement stmt = conn.createStatement();
stmt.execute("CREATE TEMP TABLE geomtest(mycirc circle)");
stmt.close();
insertCircle(conn);
retrieveCircle(conn);
conn.close();
}
private static void insertCircle(Connection conn) throws SQLException {
PGpoint center = new PGpoint(1, 2.5);
double radius = 4;
PGcircle circle = new PGcircle(center, radius);
PreparedStatement ps = conn.prepareStatement("INSERT INTO geomtest(mycirc) VALUES (?)");
ps.setObject(1, circle);
ps.executeUpdate();
ps.close();
}
private static void retrieveCircle(Connection conn) throws SQLException {
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT mycirc, area(mycirc) FROM geomtest");
rs.next();
PGcircle circle = (PGcircle)rs.getObject(1);
double area = rs.getDouble(2);
PGpoint center = circle.center;
double radius = circle.radius;
System.out.println("Center (X, Y) = (" + center.x + ", " + center.y + ")");
System.out.println("Radius = " + radius);
System.out.println("Area = " + area);
}
}

View File

@ -0,0 +1,253 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en" dir="ltr">
<head>
<title>The PostgreSQL™ JDBC Interface</title>
<meta http-equiv="Content-Type" content="text/xhtml; charset=utf-8" />
<meta name="description" content="The official site for the PostgreSQL JDBC Driver" />
<meta name="copyright" content="The PostgreSQL Global Development Group" />
<style type="text/css" media="screen" title="Normal Text">@import url("media/css/docs.css");</style>
<link rel="shortcut icon" href="media/favicon.ico" />
</head>
<body>
<div id="docHeader">
<div id="docHeaderLogo">
<a href="http://www.postgresql.org/" title="PostgreSQL"><img src="media/img/layout/hdr_left3a.png" alt="PostgreSQL" height="80" width="390" /></a>
</div>
</div>
<div id="docContainerWrap">
<div id="docContainer">
<div id="docContent">
<div class="BOOK">
<a name="POSTGRES" id="POSTGRES"></a>
<div class="TITLEPAGE">
<h1 class="TITLE">The PostgreSQL JDBC Interface</h1>
<hr />
</div>
<div class="TOC">
<h3 class="c2">Table of Contents</h3>
<dl>
<!-- <dt class="c1">Table of Contents</dt> -->
<dt>1. <a href="intro.html">Introduction</a></dt>
<dt>2. <a href="setup.html">Setting up the JDBC Driver</a></dt>
<dd>
<dl>
<dt><a href="setup.html#build">Getting the Driver</a></dt>
<dt><a href="classpath.html">Setting up the Class Path</a></dt>
<dt><a href="prepare.html">Preparing the Database Server for <acronym class="ACRONYM">JDBC</acronym></a></dt>
<dt><a href="your-database.html">Creating a Database</a></dt>
</dl>
</dd>
<dt>3. <a href="use.html">Initializing the Driver</a></dt>
<dd>
<dl>
<dt><a href="use.html#import">Importing <acronym class="ACRONYM">JDBC</acronym></a></dt>
<dt><a href="load.html">Loading the Driver</a></dt>
<dt><a href="connect.html">Connecting to the Database</a></dt>
<dd>
<dl>
<dt><a href="connect.html#connection-parameters">Connection Parameters</a></dt>
</dl>
</dd>
</dl>
</dd>
<dt>4. <a href="ssl.html">Using <acronym class="ACRONYM">SSL</acronym></a></dt>
<dd>
<dl>
<dt><a href="ssl.html#ssl-server">Configuring the Server</a></dt>
<dt><a href="ssl-client.html">Configuring the Client</a></dt>
<dd>
<dl>
<dt><a href="ssl-client.html#nonvalidating">Using SSL without Certificate Validation</a></dt>
</dl>
</dd>
<dt><a href="ssl-factory.html">Custom SSLSocketFactory</a></dt>
</dl>
</dd>
<dt>5. <a href="query.html">Issuing a Query and Processing the Result</a></dt>
<dd>
<dl>
<dt><a href="query.html#query-with-cursor">Getting results based on a cursor</a></dt>
<dt><a href="statement.html">Using the Statement or PreparedStatement Interface</a></dt>
<dt><a href="resultset.html">Using the ResultSet Interface</a></dt>
<dt><a href="update.html">Performing Updates</a></dt>
<dt><a href="ddl.html">Creating and Modifying Database Objects</a></dt>
</dl>
</dd>
<dt>6. <a href="callproc.html">Calling Stored Functions</a></dt>
<dd>
<dl>
<dt><a href="callproc.html#callproc-resultset">Obtaining a ResultSet from a stored function</a></dt>
<dd>
<dl>
<dt><a href="callproc.html#callproc-resultset-setof">From a Function Returning SETOF type</a></dt>
<dt><a href="callproc.html#callproc-resultset-refcursor">From a Function Returning a <span class="type">refcursor</span></a></dt>
</dl>
</dd>
</dl>
</dd>
<dt>7. <a href="binary-data.html">Storing Binary Data</a></dt>
<dt>8. <a href="escapes.html"><acronym class="ACRONYM">JDBC</acronym> escapes</a></dt>
<dd>
<dl>
<dt><a href="escapes.html#like-escape">Escape for like escape character</a></dt>
<dt><a href="outer-joins-escape.html">Escape for outer joins</a></dt>
<dt><a href="escapes-datetime.html">Date-time escapes</a></dt>
<dt><a href="escaped-functions.html">Escaped scalar functions</a></dt>
</dl>
</dd>
<dt>9. <a href="ext.html">PostgreSQL™ Extensions to the <acronym class="ACRONYM">JDBC</acronym> <acronym class="ACRONYM">API</acronym></a></dt>
<dd>
<dl>
<dt><a href="ext.html#extensions">Accessing the Extensions</a></dt>
<dt><a href="geometric.html">Geometric Data Types</a></dt>
<dt><a href="largeobjects.html">Large Objects</a></dt>
<dt><a href="listennotify.html">Listen / Notify</a></dt>
<dt><a href="server-prepare.html">Server Prepared Statements</a></dt>
</dl>
</dd>
<dt>10. <a href="thread.html">Using the Driver in a Multithreaded or a Servlet Environment</a></dt>
<dt>11. <a href="datasource.html">Connection Pools and Data Sources</a></dt>
<dd>
<dl>
<dt><a href="datasource.html#ds-intro">Overview</a></dt>
<dt><a href="ds-cpds.html">Application Servers: ConnectionPoolDataSource</a></dt>
<dt><a href="ds-ds.html">Applications: DataSource</a></dt>
<dt><a href="tomcat.html">Tomcat setup</a></dt>
<dt><a href="jndi.html">Data Sources and <acronym class="ACRONYM">JNDI</acronym></a></dt>
</dl>
</dd>
<dt>12. <a href="reading.html">Further Reading</a></dt>
</dl>
</div>
<div class="LOT">
<h3 class="c2">List of Tables</h3>
<dl class="LOT">
<!-- <dt class="c1">List of Tables</dt> -->
<dt>
8.1. <a href="escaped-functions.html#escape-numeric-functions-table">Supported escaped numeric functions</a>
</dt>
<dt>
8.2. <a href="escaped-functions.html#escape-string-functions-table">Supported escaped string functions</a>
</dt>
<dt>
8.3. <a href="escaped-functions.html#escape-datetime-functions-table">Supported escaped date/time functions</a>
</dt>
<dt>
8.4. <a href="escaped-functions.html#escape-misc-functions-table">Supported escaped misc functions</a>
</dt>
<dt>
11.1. <a href="ds-cpds.html#ds-cpds-props">ConnectionPoolDataSource Configuration Properties</a>
</dt>
<dt>
11.2. <a href="ds-ds.html#ds-ds-imp">DataSource Implementations</a>
</dt>
<dt>
11.3. <a href="ds-ds.html#ds-ds-props">DataSource Configuration Properties</a>
</dt>
<dt>
11.4. <a href="ds-ds.html#ds-ds-xprops">Additional Pooling DataSource Configuration Properties</a>
</dt>
</dl>
</div>
<div class="LOT">
<h3 class="c2">List of Examples</h3>
<dl class="LOT">
<!-- <dt class="c1">List of Examples</dt> -->
<dt>
5.1. <a href="query.html#query-example">Processing a Simple Query in <acronym class="ACRONYM">JDBC</acronym></a>
</dt>
<dt>
5.2. <a href="query.html#fetchsize-example">Setting fetch size to turn cursors on and off.</a>
</dt>
<dt>
5.3. <a href="update.html#delete-example">Deleting Rows in <acronym class="ACRONYM">JDBC</acronym></a>
</dt>
<dt>
5.4. <a href="ddl.html#drop-table-example">Dropping a Table in <acronym class="ACRONYM">JDBC</acronym></a>
</dt>
<dt>
6.1. <a href="callproc.html#call-function-example">Calling a built in stored function</a>
</dt>
<dt>
6.2. <a href="callproc.html#setof-resultset"> Getting SETOF type values from a function</a>
</dt>
<dt>
6.3. <a href="callproc.html#get-refcursor-from-function-call"> Getting <span class="type">refcursor</span> Value From a Function</a>
</dt>
<dt>
6.4. <a href="callproc.html#refcursor-string-example">Treating <span class="type">refcursor</span> as a cursor name</a>
</dt>
<dt>
7.1. <a href="binary-data.html#binary-data-example">Processing Binary Data in <acronym class="ACRONYM">JDBC</acronym></a>
</dt>
<dt>
8.1. <a href="escapes.html#escape-use-example">Using jdbc escapes</a>
</dt>
<dt>
9.1. <a href="geometric.html#geometric-circle-example">Using the CIRCLE datatype from <acronym class="ACRONYM">JDBC</acronym></a>
</dt>
<dt>
9.2. <a href="listennotify.html#listen-notify-example">Receiving Notifications</a>
</dt>
<dt>
9.3. <a href="server-prepare.html#server-prepared-statement-example">Using server side prepared statements</a>
</dt>
<dt>
11.1. <a href="ds-ds.html#ds-example">DataSource Code Example</a>
</dt>
<dt>
11.2. <a href="jndi.html#ds-jndi">DataSource <acronym class="ACRONYM">JNDI</acronym> Code Example</a>
</dt>
</dl>
</div>
</div> <!-- BOOK -->
<div class="NAVFOOTER">
<hr class="c2" width="100%" />
<table summary="Footer navigation table" width="100%" border="0" cellpadding="0" cellspacing="0">
<tbody>
<tr>
<td valign="top" width="33%" align="left">&nbsp;</td>
<td valign="top" width="34%" align="center">&nbsp;</td>
<td valign="top" width="33%" align="right"><a href="intro.html" accesskey="N">Next</a></td>
</tr>
<tr>
<td valign="top" width="33%" align="left">&nbsp;</td>
<td valign="top" width="34%" align="center">&nbsp;</td>
<td valign="top" width="33%" align="right">Chapter 1. Introduction</td>
</tr>
</tbody>
</table>
</div>
</div> <!--docContent -->
<div id="docComments"></div>
<div id="docFooter">
<a class="navFooter" href="http://www.postgresql.org/about/privacypolicy">Privacy Policy</a> |
<a class="navFooter" href="http://www.postgresql.org/about/">About PostgreSQL</a><br/>
Copyright &copy; 1996-2013 The PostgreSQL Global Development Group
</div> <!-- pgFooter -->
</div> <!-- docContainer -->
</div> <!-- docContainerWrap -->
</body>

View File

@ -0,0 +1,22 @@
---
layout: default_docs
title: Chapter 1. Introduction
header: Chapter 1. Introduction
resource: media
previoustitle: The PostgreSQL™ JDBC Interface
previous: index.html
nexttitle: Chapter 2. Setting up the JDBC Driver
next: setup.html
---
JDBC is a core API of Java 1.1 and later. It provides a standard set of interfaces
to SQL-compliant databases.
PostgreSQL™ provides a *type 4* JDBC driver. Type 4 indicates that the driver is
written in Pure Java, and communicates in the database system's own network protocol.
Because of this, the driver is platform independent; once compiled, the driver
can be used on any system.
This manual is not intended as a complete guide to JDBC programming, but should
help to get you started. For more information refer to the standard JDBC API
documentation. Also, take a look at the examples included with the source.

View File

@ -0,0 +1,68 @@
---
layout: default_docs
title: Data Sources and JNDI
header: Chapter 11. Connection Pools and Data Sources
resource: media
previoustitle: Tomcat setup
previous: tomcat.html
nexttitle: Chapter 12. Further Reading
next: reading.html
---
All the `ConnectionPoolDataSource` and `DataSource` implementations can be stored
in JNDI. In the case of the nonpooling implementations, a new instance will be
created every time the object is retrieved from JNDI, with the same settings as
the instance that was stored. For the pooling implementations, the same instance
will be retrieved as long as it is available (e.g., not a different JVM retrieving
the pool from JNDI), or a new instance with the same settings created otherwise.
In the application server environment, typically the application server's
`DataSource` instance will be stored in JNDI, instead of the PostgreSQL™
`ConnectionPoolDataSource` implementation.
In an application environment, the application may store the `DataSource` in JNDI
so that it doesn't have to make a reference to the `DataSource` available to all
application components that may need to use it. An example of this is shown in
[Example 11.2, “`DataSource` JNDI Code Example”](jndi.html#ds-jndi).
<a name="ds-jndi"></a>
**Example 11.2. `DataSource` JNDI Code Example**
Application code to initialize a pooling `DataSource` and add it to JNDI might
look like this:
`PGPoolingDataSource source = new PGPoolingDataSource();`
`source.setDataSourceName("A Data Source");`
`source.setServerName("localhost");`
`source.setDatabaseName("test");`
`source.setUser("testuser");`
`source.setPassword("testpassword");`
`source.setMaxConnections(10);`
`new InitialContext().rebind("DataSource", source);`
Then code to use a connection from the pool might look like this:
<pre><code>
Connection conn = null;
try
{
DataSource source = (DataSource)new InitialContext().lookup("DataSource");
conn = source.getConnection();
// use connection
}
catch (SQLException e)
{
// log error
}
catch (NamingException e)
{
// DataSource wasn't found in JNDI
}
finally
{
if (con != null)
{
try { conn.close(); } catch (SQLException e) {}
}
}
</code></pre>

View File

@ -0,0 +1,20 @@
---
layout: default_docs
title: Large Objects
header: Chapter 9. PostgreSQL™ Extensions to the JDBC API
resource: media
previoustitle: Geometric Data Types
previous: geometric.html
nexttitle: Listen / Notify
next: listennotify.html
---
Large objects are supported in the standard JDBC specification. However, that
interface is limited, and the API provided by PostgreSQL™ allows for random
access to the objects contents, as if it was a local file.
The org.postgresql.largeobject package provides to Java the libpq C interface's
large object API. It consists of two classes, `LargeObjectManager`, which deals
with creating, opening and deleting large objects, and `LargeObject` which deals
with an individual object. For an example usage of this API, please see
[Example 7.1, “Processing Binary Data in JDBC”](binary-data.html#binary-data-example).

View File

@ -0,0 +1,148 @@
---
layout: default_docs
title: Listen / Notify
header: Chapter 9. PostgreSQL™ Extensions to the JDBC API
resource: media
previoustitle: Large Objects
previous: largeobjects.html
nexttitle: Server Prepared Statements
next: server-prepare.html
---
Listen and Notify provide a simple form of signal or interprocess communication
mechanism for a collection of processes accessing the same PostgreSQL™ database.
For more information on notifications consult the main server documentation. This
section only deals with the JDBC specific aspects of notifications.
Standard `LISTEN`, `NOTIFY`, and `UNLISTEN` commands are issued via the standard
`Statement` interface. To retrieve and process retrieved notifications the
`Connection` must be cast to the PostgreSQL™ specific extension interface
`PGConnection`. From there the `getNotifications()` method can be used to retrieve
any outstanding notifications.
### Note
> A key limitation of the JDBC driver is that it cannot receive asynchronous
notifications and must poll the backend to check if any notifications were issued.
<a name="listen-notify-example"></a>
**Example 9.2. Receiving Notifications**
<pre><code>
import java.sql.*;
public class NotificationTest
{
public static void main(String args[]) throws Exception
{
Class.forName("org.postgresql.Driver");
String url = "jdbc:postgresql://localhost:5432/test";
// Create two distinct connections, one for the notifier
// and another for the listener to show the communication
// works across connections although this example would
// work fine with just one connection.
Connection lConn = DriverManager.getConnection(url,"test","");
Connection nConn = DriverManager.getConnection(url,"test","");
// Create two threads, one to issue notifications and
// the other to receive them.
Listener listener = new Listener(lConn);
Notifier notifier = new Notifier(nConn);
listener.start();
notifier.start();
}
}
</code></pre>
<pre><code>
class Listener extends Thread
{
private Connection conn;
private org.postgresql.PGConnection pgconn;
Listener(Connection conn) throws SQLException
{
this.conn = conn;
this.pgconn = conn.unwrap(org.postgresql.PGConnection.class);
Statement stmt = conn.createStatement();
stmt.execute("LISTEN mymessage");
stmt.close();
}
public void run()
{
while (true)
{
try
{
// issue a dummy query to contact the backend
// and receive any pending notifications.
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT 1");
rs.close();
stmt.close();
org.postgresql.PGNotification notifications[] = pgconn.getNotifications();
if (notifications != null)
{
for (int i=0; i&lt;notifications.length; i++)
System.out.println("Got notification: " + notifications[i].getName());
}
// wait a while before checking again for new
// notifications
Thread.sleep(500);
}
catch (SQLException sqle)
{
sqle.printStackTrace();
}
catch (InterruptedException ie)
{
ie.printStackTrace();
}
}
}
}
</code></pre>
<pre><code>
class Notifier extends Thread
{
private Connection conn;
public Notifier(Connection conn)
{
this.conn = conn;
}
public void run()
{
while (true)
{
try
{
Statement stmt = conn.createStatement();
stmt.execute("NOTIFY mymessage");
stmt.close();
Thread.sleep(2000);
}
catch (SQLException sqle)
{
sqle.printStackTrace();
}
catch (InterruptedException ie)
{
ie.printStackTrace();
}
}
}
}
</code></pre>

View File

@ -0,0 +1,47 @@
---
layout: default_docs
title: Loading the Driver
header: Chapter 3. Initializing the Driver
resource: media
previoustitle: Chapter 3. Initializing the Driver
previous: use.html
nexttitle: Connecting to the Database
next: connect.html
---
Before you can connect to a database, you need to load the driver. There are two
methods available, and it depends on your code which is the best one to use.
In the first method, your code implicitly loads the driver using the `Class.forName()`
method. For PostgreSQL™, you would use:
Class.forName("org.postgresql.Driver");
This will load the driver, and while loading, the driver will automatically
register itself with JDBC.
### Note
The `forName()` method can throw a `ClassNotFoundException` if the driver is not
available.
This is the most common method to use, but restricts your code to use just PostgreSQL™.
If your code may access another database system in the future, and you do not
use any PostgreSQL™-specific extensions, then the second method is advisable.
The second method passes the driver as a parameter to the JVM as it starts, using
the `-D` argument. Example:
`java -Djdbc.drivers=org.postgresql.Driver example.ImageViewer`
In this example, the JVM will attempt to load the driver as part of its initialization.
Once done, the ImageViewer is started.
Now, this method is the better one to use because it allows your code to be used
with other database packages without recompiling the code. The only thing that
would also change is the connection URL, which is covered next.
One last thing: When your code then tries to open a `Connection`, and you get a
No driver available `SQLException` being thrown, this is probably caused by the
driver not being in the class path, or the value in the parameter not being
correct.

View File

@ -0,0 +1,450 @@
/* PostgreSQL.org Documentation Style */
@import url("global.css");
@import url("table.css");
@import url("text.css");
body {
font-size: 76%;
}
div.NAVHEADER table {
margin-left: 0;
}
/* Container Definitions */
#docContainerWrap {
text-align: center; /* Win IE5 */
}
#docContainer {
margin: 0 auto;
width: 90%;
padding-bottom: 2em;
display: block;
text-align: left; /* Win IE5 */
}
#docHeader {
background-image: url("../img/docs/bg_hdr.png");
height: 83px;
margin: 0px;
padding: 0px;
display: block;
}
#docHeaderLogo {
position: relative;
width: 206px;
height: 83px;
border: 0px;
padding: 0px;
margin: 0 0 0 20px;
}
#docHeaderLogo img {
border: 0px;
}
#docNavSearchContainer {
padding-bottom: 2px;
}
#docNav, #docVersions {
position: relative;
text-align: left;
margin-left: 10px;
margin-top: 5px;
color: #666;
font-size: 0.95em;
}
#docSearch {
position: relative;
text-align: right;
padding: 0;
margin: 0;
color: #666;
}
#docTextSize {
text-align: right;
white-space: nowrap;
margin-top: 7px;
font-size: 0.95em;
}
#docSearch form {
position: relative;
top: 5px;
right: 0;
margin: 0; /* need for IE 5.5 OSX */
text-align: right; /* need for IE 5.5 OSX */
white-space: nowrap; /* for Opera */
}
#docSearch form label {
color: #666;
font-size: 0.95em;
}
#docSearch form input {
font-size: 0.95em;
}
#docSearch form #submit {
font-size: 0.95em;
background: #7A7A7A;
color: #fff;
border: 1px solid #7A7A7A;
padding: 1px 4px;
}
#docSearch form #q {
width: 170px;
font-size: 0.95em;
border: 1px solid #7A7A7A;
background: #E1E1E1;
color: #000000;
padding: 2px;
}
.frmDocSearch {
padding: 0;
margin: 0;
display: inline;
}
.inpDocSearch {
padding: 0;
margin: 0;
color: #000;
}
#docContent {
position: relative;
margin-left: 10px;
margin-right: 10px;
margin-top: 40px;
}
#docFooter {
position: relative;
font-size: 0.9em;
color: #666;
line-height: 1.3em;
margin-left: 10px;
margin-right: 10px;
}
#docComments {
margin-top: 10px;
}
#docClear {
clear: both;
margin: 0;
padding: 0;
}
/* Heading Definitions */
h1, h2, h3 {
font-weight: bold;
margin-top: 2ex;
}
h1 {
font-size: 1.4em;
}
h2 {
font-size: 1.2em !important;
}
h3 {
font-size: 1.1em;
}
h1 a:hover {
color: #EC5800;
text-decoration: none;
}
h2 a:hover,
h3 a:hover,
h4 a:hover {
color: #666666;
text-decoration: none;
}
/* Text Styles */
div.SECT2 {
margin-top: 4ex;
}
div.SECT3 {
margin-top: 3ex;
margin-left: 3ex;
}
.txtCurrentLocation {
font-weight: bold;
}
p, ol, ul, li {
line-height: 1.5em;
}
.txtCommentsWrap {
border: 2px solid #F5F5F5;
width: 100%;
}
.txtCommentsContent {
background: #F5F5F5;
padding: 3px;
}
.txtCommentsPoster {
float: left;
}
.txtCommentsDate {
float: right;
}
.txtCommentsComment {
padding: 3px;
}
#docContainer p code,
#docContainer ul code,
#docContainer pre code,
#docContainer pre tt,
#docContainer pre pre,
#docContainer tt tt,
#docContainer tt code,
#docContainer tt pre {
font-size: 1.5em;
}
pre.LITERALLAYOUT,
.SCREEN,
.SYNOPSIS,
.PROGRAMLISTING,
.REFSYNOPSISDIV p,
table.CAUTION,
table.WARNING,
blockquote.NOTE,
blockquote.TIP,
table.CALSTABLE {
-moz-box-shadow: 3px 3px 5px #DFDFDF;
-webkit-box-shadow: 3px 3px 5px #DFDFDF;
-khtml-box-shadow: 3px 3px 5px #DFDFDF;
-o-box-shadow: 3px 3px 5px #DFDFDF;
box-shadow: 3px 3px 5px #DFDFDF;
}
pre.LITERALLAYOUT,
.SCREEN,
.SYNOPSIS,
.PROGRAMLISTING,
.REFSYNOPSISDIV p,
table.CAUTION,
table.WARNING,
blockquote.NOTE,
blockquote.TIP {
color: black;
border-width: 1px;
border-style: solid;
padding: 2ex;
margin: 2ex 0 2ex 2ex;
overflow: auto;
-moz-border-radius: 8px;
-webkit-border-radius: 8px;
-khtml-border-radius: 8px;
border-radius: 8px;
}
pre.LITERALLAYOUT,
pre.SYNOPSIS,
pre.PROGRAMLISTING,
.REFSYNOPSISDIV p,
.SCREEN {
border-color: #CFCFCF;
background-color: #F7F7F7;
}
blockquote.NOTE,
blockquote.TIP {
border-color: #DBDBCC;
background-color: #EEEEDD;
padding: 14px;
width: 572px;
}
blockquote.NOTE,
blockquote.TIP,
table.CAUTION,
table.WARNING {
margin: 4ex auto;
}
blockquote.NOTE p,
blockquote.TIP p {
margin: 0;
}
blockquote.NOTE pre,
blockquote.NOTE code,
blockquote.TIP pre,
blockquote.TIP code {
margin-left: 0;
margin-right: 0;
-moz-box-shadow: none;
-webkit-box-shadow: none;
-khtml-box-shadow: none;
-o-box-shadow: none;
box-shadow: none;
}
.emphasis,
.c2 {
font-weight: bold;
}
.REPLACEABLE {
font-style: italic;
}
/* Table Styles */
table {
margin-left: 2ex;
}
table.CALSTABLE td,
table.CALSTABLE th,
table.CAUTION td,
table.CAUTION th,
table.WARNING td,
table.WARNING th {
border-style: solid;
}
table.CALSTABLE,
table.CAUTION,
table.WARNING {
border-spacing: 0;
border-collapse: collapse;
}
table.CALSTABLE
{
margin: 2ex 0 2ex 2ex;
background-color: #E0ECEF;
border: 2px solid #A7C6DF;
}
table.CALSTABLE tr:hover td
{
background-color: #EFEFEF;
}
table.CALSTABLE td {
background-color: #FFF;
}
table.CALSTABLE td,
table.CALSTABLE th {
border: 1px solid #A7C6DF;
padding: 0.5ex 0.5ex;
}
table.CAUTION,
table.WARNING {
border-collapse: separate;
display: block;
padding: 0;
max-width: 600px;
}
table.CAUTION {
background-color: #F5F5DC;
border-color: #DEDFA7;
}
table.WARNING {
background-color: #FFD7D7;
border-color: #DF421E;
}
table.CAUTION td,
table.CAUTION th,
table.WARNING td,
table.WARNING th {
border-width: 0;
padding-left: 2ex;
padding-right: 2ex;
}
table.CAUTION td,
table.CAUTION th {
border-color: #F3E4D5
}
table.WARNING td,
table.WARNING th {
border-color: #FFD7D7;
}
td.c1,
td.c2,
td.c3,
td.c4,
td.c5,
td.c6 {
font-size: 1.1em;
font-weight: bold;
border-bottom: 0px solid #FFEFEF;
padding: 1ex 2ex 0;
}
/* Link Styles */
#docNav a {
font-weight: bold;
}
a:link,
a:visited,
a:active,
a:hover {
text-decoration: underline;
}
a:link,
a:active {
color:#0066A2;
}
a:visited {
color:#004E66;
}
a:hover {
color:#000000;
}
#docFooter a:link,
#docFooter a:visited,
#docFooter a:active {
color:#666;
}
#docContainer code.FUNCTION tt {
font-size: 1em;
}

View File

@ -0,0 +1,98 @@
/*
PostgreSQL.org - Global Styles
*/
body {
margin: 0;
padding: 0;
font-family: verdana, sans-serif;
font-size: 69%;
color: #000;
background-color: #fff;
}
h1 {
font-size: 1.4em;
font-weight: bold;
margin-top: 0em;
margin-bottom: 0em;
}
h2 {
font-size: 1.2em;
margin: 1.2em 0em 1.2em 0em;
font-weight: bold;
}
h3 {
font-size: 1.0em;
margin: 1.2em 0em 1.2em 0em;
font-weight: bold;
}
h4 {
font-size: 0.95em;
margin: 1.2em 0em 1.2em 0em;
font-weight: normal;
}
h5 {
font-size: 0.9em;
margin: 1.2em 0em 1.2em 0em;
font-weight: normal;
}
h6 {
font-size: 0.85em;
margin: 1.2em 0em 1.2em 0em;
font-weight: normal;
}
img {
border: 0;
}
ol, ul, li {/*
list-style: none;*/
font-size: 1.0em;
line-height: 1.2em;
margin-top: 0.2em;
margin-bottom: 0.1em;
}
p {
font-size: 1.0em;
line-height: 1.2em;
margin: 1.2em 0em;
}
td p {
margin: 0em 0em 1.2em;
}
li > p {
margin-top: 0.2em;
}
pre {
font-family: monospace;
font-size: 1.0em;
}
div#pgContentWrap code {
font-size: 1.2em;
padding: 1em;
margin: 2ex 0 2ex 2ex;
background: #F7F7F7;
border: 1px solid #CFCFCF;
-moz-border-radius: 8px;
-webkit-border-radius: 8px;
-khtml-border-radius: 8px;
border-radius: 8px;
display: block;
overflow: auto;
}
strong, b {
font-weight: bold;
}

View File

@ -0,0 +1,101 @@
/*
PostgreSQL.org - Table Styles
*/
div.tblBasic h2 {
margin: 25px 0 .5em 0;
}
div.tblBasic table {
background: #F5F5F5 url(../img/layout/nav_tbl_top_lft.png) top left no-repeat;
margin-left: 2ex;
margin-bottom: 15px;
}
div.tblBasic table th {
padding-top: 20px;
border-bottom: 1px solid #EFEFEF;
vertical-align: bottom;
}
div.tblBasic table td {
border-bottom: 1px solid #EFEFEF;
}
div.tblBasic table th,
div.tblBasic table td {
padding: 8px 11px;
color: #555555;
}
div.tblBasic table td.indented {
text-indent: 30px;
}
div.tblBasic table.tblCompact td {
padding: 3px 3px;
}
div.tblBasic table tr.lastrow td {
border-bottom: none;
padding-bottom: 13px;
}
div.tblBasic table.tblCompact tr.lastrow td {
padding-bottom: 3px;
}
div.tblBasic table tr.lastrow td.colFirstT,
div.tblBasic table tr.lastrow td.colFirst {
background: url(../img/layout/nav_tbl_btm_lft.png) bottom left no-repeat;
}
div.tblBasic table.tblBasicGrey th.colLast,
div.tblBasic table.tblCompact th.colLast {
background: #F5F5F5 url(../img/layout/nav_tbl_top_rgt.png) top right no-repeat;
}
div.tblBasic table.tblBasicGrey tr.lastrow td.colLastT,
div.tblBasic table.tblBasicGrey tr.lastrow td.colLast,
div.tblBasic table.tblCompact tr.lastrow td.colLast,
div.tblBasic table.tblCompact tr.lastrow td.colLastT{
background: #F5F5F5 url(../img/layout/nav_tbl_btm_rgt.png) bottom right no-repeat;
}
div.tblBasic table.tblBasicGrey tr.firstrow td.colLastT,
div.tblBasic table.tblBasicGrey tr.firstrow td.colLast,
div tblBasic table.tblCompact tr.firstrow td.colLast {
background: #F5F5F5 url(../img/layout/nav_tbl_top_rgt.png) top right no-repeat;
}
div.tblBasic table th.colMid,
div.tblBasic table td.colMid,
div.tblBasic table th.colLast,
div.tblBasic table td.colLast {
background-color: #F5F5F5 ;
}
div.tblBasic table th.colLastC,
div.tblBasic table td.colFirstC,
div.tblBasic table td.colLastC {
text-align: center;
}
div.tblBasic table th.colLastR,
div.tblBasic table td.colFirstR,
div.tblBasic table td.colLastR {
text-align: right;
}
div.tblBasic table td.colFirstT,
div.tblBasic table td.colMidT,
div.tblBasic table td.colLastT {
vertical-align: top;
}
div.tblBasic table th.colLastRT,
div.tblBasic table td.colFirstRT,
div.tblBasic table td.colLastRT {
text-align: right;
vertical-align: top;
}

View File

@ -0,0 +1,162 @@
/*
PostgreSQL.org - Text Styles
*/
/* Heading Definitions */
h1 {
color: #EC5800;
}
h2 {
color: #666;
}
h3 {
color: #666;
}
h4 {
color: #666;
}
/* Text Styles */
.txtColumn1 {
width: 50%;
line-height: 1.3em;
}
.txtColumn2 {
width: 50%;
line-height: 1.5em;
}
.txtCurrentLocation {
font-weight: bold;
}
.txtDivider {
font-size: 0.8em;
color: #E1E1E1;
padding-left: 4px;
padding-right: 4px;
}
.txtNewsEvent {
font-size: 0.9em;
color: #0094C7;
}
.txtDate {
font-size: 0.9em;
color: #666;
}
.txtMediumGrey {
color: #666;
}
.txtFormLabel {
color: #666;
font-weight: bold;
text-align: right;
vertical-align: top;
}
.txtRequiredField {
color: #EC5800;
}
.txtImportant {
color: #EC5800;
}
.txtOffScreen {
position: absolute;
left: -1999px;
width: 1990px;
}
#txtFrontFeatureHeading {
padding-bottom: 1.1em;
}
#txtFrontFeatureLink a {
font-size: 1.2em;
font-weight: bold;
padding-left: 5px;
}
#txtFrontUserText {
font-size: 1.0em;
color: #666;
margin-top: 12px;
}
#txtFrontUserName {
font-size: 0.9em;
color: #666;
margin-top: 9px;
font-weight: bold;
}
#txtFrontUserLink {
font-size: 0.9em;
color: #666;
margin-top: 11px;
margin-left: 1px;
}
#txtFrontUserLink img {
padding-right: 5px;
}
#txtFrontSupportUsText {
font-size: 1.0em;
margin-top: 9px;
}
#txtFrontSupportUsLink {
font-size: 0.9em;
margin-top: 6px;
}
#txtFrontSupportUsLink img {
padding-right: 7px;
}
/* Link Styles */
a:link { color:#0085B0; text-decoration: underline; }
a:visited { color:#004E66; text-decoration: underline; }
a:active { color:#0085B0; text-decoration: underline; }
a:hover { color:#000000; text-decoration: underline; }
#pgFooter a:link { color:#666; text-decoration: underline; }
#pgFooter a:visited { color:#666; text-decoration: underline; }
#pgFooter a:active { color:#666; text-decoration: underline; }
#pgFooter a:hover { color:#000000; text-decoration: underline; }
#txtFrontUserName a:link { color:#666; text-decoration: underline; }
#txtFrontUserName a:visited { color:#666; text-decoration: underline; }
#txtFrontUserName a:active { color:#666; text-decoration: underline; }
#txtFrontUserName a:hover { color:#000; text-decoration: underline; }
#txtArchives a:visited { color:#00536E; text-decoration: underline; }
#txtArchives pre { word-wrap: break-word; font-size: 150%; }
#txtArchives tt { word-wrap: break-word; font-size: 150%; }
#pgFrontUSSContainer h2, #pgFrontUSSContainer h3 {
margin: 0;
padding: 0;
}
#pgFrontNewsEventsContainer h2, #pgFrontNewsEventsContainer h3 {
margin: 0;
padding: 0;
}
#pgFrontNewsEventsContainer h3 img {
margin-bottom: 10px;
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 173 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 92 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 218 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 212 B

View File

@ -0,0 +1,17 @@
---
layout: default_docs
title: Escape for outer joins
header: Chapter 8. JDBC escapes
resource: media
previoustitle: Chapter 8. JDBC escapes
previous: escapes.html
nexttitle: Date-time escapes
next: escapes-datetime.html
---
You can specify outer joins using the following syntax: `{oj table (LEFT|RIGHT|FULL) OUTER JOIN (table | outer-join)
ON search-condition }`
For example :
`rs = stmt.executeQuery( "select * from {oj a left outer join b on (a.i=b.i)} ");`

View File

@ -0,0 +1,25 @@
---
layout: default_docs
title: Preparing the Database Server for JDBC
header: Chapter 2. Setting up the JDBC Driver
resource: media
previoustitle: Setting up the Class Path
previous: classpath.html
nexttitle: Creating a Database
next: your-database.html
---
Because Java does not support using unix sockets the PostgreSQL™ server must be
configured to allow TCP/IP connections. Starting with server version 8.0 TCP/IP
connections are allowed from `localhost`. To allow connections to other interfaces
than the loopback interface, you must modify the `postgresql.conf` file's `listen_addresses`
setting.
For server versions prior to 8.0 the server does not listen on any interface by
default, and you must set `tcpip_socket = true` in the `postgresql.conf` file.
Once you have made sure the server is correctly listening for TCP/IP connections
the next step is to verify that users are allowed to connect to the server. Client
authentication is setup in `pg_hba.conf`. Refer to the main PostgreSQL™ documentation
for details. The JDBC driver supports the `trust`, `ident`, `password`, `md5`, and
`crypt` authentication methods.

View File

@ -0,0 +1,113 @@
---
layout: default_docs
title: Chapter 5. Issuing a Query and Processing the Result
header: Chapter 5. Issuing a Query and Processing the Result
resource: media
previoustitle: Custom SSLSocketFactory
previous: ssl-factory.html
nexttitle: Using the Statement or PreparedStatement Interface
next: statement.html
---
**Table of Contents**
* [Getting results based on a cursor](query.html#query-with-cursor)
* [Using the `Statement` or `PreparedStatement` Interface](statement.html)
* [Using the `ResultSet` Interface](resultset.html)
* [Performing Updates](update.html)
* [Creating and Modifying Database Objects](ddl.html)
Any time you want to issue SQL statements to the database, you require a `Statement`
or `PreparedStatement` instance. Once you have a `Statement` or `PreparedStatement`,
you can use issue a query. This will return a `ResultSet` instance, which contains
the entire result (see the section called [“Getting results based on a cursor”](query.html#query-with-cursor)
here for how to alter this behaviour). [Example 5.1, “Processing a Simple Query in JDBC”](query.html#query-example)
illustrates this process.
<a name="query-example"></a>
**Example 5.1. Processing a Simple Query in JDBC**
This example will issue a simple query and print out the first column of each
row using a `Statement`.
`Statement st = conn.createStatement();`
`ResultSet rs = st.executeQuery("SELECT * FROM mytable WHERE columnfoo = 500");`
`while (rs.next())`
`{`
&nbsp;&nbsp;&nbsp;`System.out.print("Column 1 returned ");`
&nbsp;&nbsp;&nbsp;`System.out.println(rs.getString(1));`
`}`
`rs.close();`
`st.close();`
This example issues the same query as before but uses a `PreparedStatement` and
a bind value in the query.
`int foovalue = 500;`
`PreparedStatement st = conn.prepareStatement("SELECT * FROM mytable WHERE columnfoo = ?");`
`st.setInt(1, foovalue);`
`ResultSet rs = st.executeQuery();`
`while (rs.next())`
`{`
&nbsp;&nbsp;&nbsp;`System.out.print("Column 1 returned ");`
&nbsp;&nbsp;&nbsp;`System.out.println(rs.getString(1));`
`}`
`rs.close();`
`st.close();`
<a name="query-with-cursor"></a>
# Getting results based on a cursor
By default the driver collects all the results for the query at once. This can
be inconvenient for large data sets so the JDBC driver provides a means of basing
a `ResultSet` on a database cursor and only fetching a small number of rows.
A small number of rows are cached on the client side of the connection and when
exhausted the next block of rows is retrieved by repositioning the cursor.
### Note
> Cursor based `ResultSets` cannot be used in all situations. There a number of
restrictions which will make the driver silently fall back to fetching the
whole `ResultSet` at once.
* The connection to the server must be using the V3 protocol. This is the default
for (and is only supported by) server versions 7.4 and later.
* The `Connection` must not be in autocommit mode. The backend closes cursors at
the end of transactions, so in autocommit mode the backend will have
closed the cursor before anything can be fetched from it.
*The `Statement` must be created with a `ResultSet` type of `ResultSet.TYPE_FORWARD_ONLY`.
This is the default, so no code will need to be rewritten to take advantage
of this, but it also means that you cannot scroll backwards or otherwise
jump around in the `ResultSet`.
* The query given must be a single statement, not multiple statements strung
together with semicolons.
<a name="fetchsize-example"></a>
**Example 5.2. Setting fetch size to turn cursors on and off.**
Changing code to cursor mode is as simple as setting the fetch size of the
`Statement` to the appropriate size. Setting the fetch size back to 0 will cause
all rows to be cached (the default behaviour).
`// make sure autocommit is off`
`conn.setAutoCommit(false);`
`Statement st = conn.createStatement();`<br /><br />
`// Turn use of the cursor on.`
`st.setFetchSize(50);`
`ResultSet rs = st.executeQuery("SELECT * FROM mytable");`
`while (rs.next())`
`{`
&nbsp;&nbsp;&nbsp;`System.out.print("a row was returned.");`
`}`
`rs.close();`<br /><br />
`// Turn the cursor off.`
`st.setFetchSize(0);`
`rs = st.executeQuery("SELECT * FROM mytable");`
`while (rs.next())`
`{`
&nbsp;&nbsp;&nbsp;`System.out.print("many rows were returned.");`
`}`
`rs.close();`<br /><br />
`// Close the statement.`
`st.close();`

View File

@ -0,0 +1,18 @@
---
layout: default_docs
title: Chapter 12. Further Reading
header: Chapter 12. Further Reading
resource: media
previoustitle: Data Sources and JNDI
previous: jndi.html
nexttitle: The PostgreSQL™ JDBC Interface
next: index.html
---
If you have not yet read it, you are advised you read the JDBC API Documentation
(supplied with Oracle's JDK) and the JDBC Specification. Both are available from
[http://www.oracle.com/technetwork/java/javase/jdbc/index.html](http://www.oracle.com/technetwork/java/javase/jdbc/index.html).
[http://jdbc.postgresql.org/index.html](http://jdbc.postgresql.org/index.html)
contains updated information not included in this manual including Javadoc class
documentation and a FAQ. Additionally it offers precompiled drivers.

View File

@ -0,0 +1,19 @@
---
layout: default_docs
title: Using the ResultSet Interface
header: Chapter 5. Issuing a Query and Processing the Result
resource: media
previoustitle: Using the Statement or PreparedStatement Interface
previous: statement.html
nexttitle: Performing Updates
next: update.html
---
The following must be considered when using the `ResultSet` interface:
* Before reading any values, you must call `next()`. This returns true if there
is a result, but more importantly, it prepares the row for processing.
* You must close a `ResultSet` by calling `close()` once you have finished using
it.
* Once you make another query with the `Statement` used to create a `ResultSet`,
the currently open `ResultSet` instance is closed automatically.

View File

@ -0,0 +1,121 @@
---
layout: default_docs
title: Server Prepared Statements
header: Chapter 9. PostgreSQL™ Extensions to the JDBC API
resource: media
previoustitle: Listen / Notify
previous: listennotify.html
nexttitle: Chapter 10. Using the Driver in a Multithreaded or a Servlet Environment
next: thread.html
---
The PostgreSQL™ server allows clients to compile sql statements that are expected
to be reused to avoid the overhead of parsing and planning the statement for every
execution. This functionality is available at the SQL level via PREPARE and EXECUTE
beginning with server version 7.3, and at the protocol level beginning with server
version 7.4, but as Java developers we really just want to use the standard
`PreparedStatement` interface.
### Note
> Previous versions of the driver used PREPARE and EXECUTE to implement
server-prepared statements. This is supported on all server versions beginning
with 7.3, but produced application-visible changes in query results, such as
missing ResultSet metadata and row update counts. The current driver uses the V3
protocol-level equivalents which avoid these changes in query results, but the
V3 protocol is only available beginning with server version 7.4. Enabling server-prepared
statements will have no affect when connected to a 7.3 server or when explicitly
using the V2 protocol to connect to a 7.4 server.
There are a number of ways to enable server side prepared statements depending on
your application's needs. The general method is to set a threshold for a
`PreparedStatement`. An internal counter keeps track of how many times the
statement has been executed and when it reaches the threshold it will start to
use server side prepared statements.
### Note
> Server side prepared statements are planned only once by the server. This avoids
the cost of replanning the query every time, but also means that the planner
cannot take advantage of the particular parameter values used in a particular
execution of the query. You should be cautious about enabling the use of server
side prepared statements globally.
<a name="server-prepared-statement-example"></a>
**Example 9.3. Using server side prepared statements**
import java.sql.*;
public class ServerSidePreparedStatement
{
public static void main(String args[]) throws Exception
{
Class.forName("org.postgresql.Driver");
String url = "jdbc:postgresql://localhost:5432/test";
Connection conn = DriverManager.getConnection(url,"test","");
PreparedStatement pstmt = conn.prepareStatement("SELECT ?");
// cast to the pg extension interface
org.postgresql.PGStatement pgstmt = pstmt.unwrap(org.postgresql.PGStatement.class);
// on the third execution start using server side statements
pgstmt.setPrepareThreshold(3);
for (int i=1; i<=5; i++)
{
pstmt.setInt(1,i);
boolean usingServerPrepare = pgstmt.isUseServerPrepare();
ResultSet rs = pstmt.executeQuery();
rs.next();
System.out.println("Execution: "+i+", Used server side: " + usingServerPrepare + ", Result: "+rs.getInt(1));
rs.close();
}
pstmt.close();
conn.close();
}
}
Which produces the expected result of using server side prepared statements upon
the third execution.
`Execution: 1, Used server side: false, Result: 1`
`Execution: 2, Used server side: false, Result: 2`
`Execution: 3, Used server side: true, Result: 3`
`Execution: 4, Used server side: true, Result: 4`
`Execution: 5, Used server side: true, Result: 5`
The example shown above requires the programmer to use PostgreSQL™ specific code
in a supposedly portable API which is not ideal. Also it sets the threshold only
for that particular statement which is some extra typing if we wanted to use that
threshold for every statement. Let's take a look at the other ways to set the
threshold to enable server side prepared statements. There is already a hierarchy
in place above a `PreparedStatement`, the `Connection` it was created from, and
above that the source of the connection be it a `Datasource` or a URL. The server
side prepared statement threshold can be set at any of these levels such that
the value will be the default for all of it's children.
`// pg extension interfaces`
`org.postgresql.PGConnection pgconn;`
`org.postgresql.PGStatement pgstmt;`
`// set a prepared statement threshold for connections created from this url`
`String url = "jdbc:postgresql://localhost:5432/test?prepareThreshold=3";`
`// see that the connection has picked up the correct threshold from the url`
`Connection conn = DriverManager.getConnection(url,"test","");`
`pgconn = conn.unwrap(org.postgresql.PGConnection.class);`
`System.out.println(pgconn.getPrepareThreshold()); // Should be 3`
`// see that the statement has picked up the correct threshold from the connection`
`PreparedStatement pstmt = conn.prepareStatement("SELECT ?");`
`pgstmt = pstmt.unwrap(org.postgresql.PGStatement.class);`
`System.out.println(pgstmt.getPrepareThreshold()); // Should be 3`
`// change the connection's threshold and ensure that new statements pick it up`
`pgconn.setPrepareThreshold(5);`
`PreparedStatement pstmt = conn.prepareStatement("SELECT ?");`
`pgstmt = pstmt.unwrap(org.postgresql.PGStatement.class);`
`System.out.println(pgstmt.getPrepareThreshold()); // Should be 5`

View File

@ -0,0 +1,44 @@
---
layout: default_docs
title: Chapter 2. Setting up the JDBC Driver
header: Chapter 2. Setting up the JDBC Driver
resource: media
previoustitle: Chapter 1. Introduction
previous: intro.html
nexttitle: Setting up the Class Path
next: classpath.html
---
**Table of Contents**
* [Getting the Driver](setup.html#build)
* [Setting up the Class Path](classpath.html)
* [Preparing the Database Server for JDBC](prepare.html)
* [Creating a Database](your-database.html)
This section describes the steps you need to take before you can write or run
programs that use the JDBC interface.
<a name="build"></a>
# Getting the Driver
Precompiled versions of the driver can be downloaded from the [PostgreSQL™ JDBC web site](http://jdbc.postgresql.org).
Alternatively you can build the driver from source, but you should only need to
do this if you are making changes to the source code. To build the JDBC driver,
you need Ant 1.5 or higher and a JDK. Ant is a special tool for building Java-based
packages. It can be downloaded from the [Ant web site](http://ant.apache.org/index.html).
If you have several Java compilers installed, it depends on the Ant configuration
which one gets used. Precompiled Ant distributions are typically set up to read
a file `.antrc` in the current user's home directory for configuration. For example,
to use a different JDK than the default, this may work:
`JAVA_HOME=/usr/local/jdk1.6.0_07`
`JAVACMD=$JAVA_HOME/bin/java`
To compile the driver simply run **ant** in the top level directory. The compiled
driver will be placed in `jars/postgresql.jar`. The resulting driver will be built
for the version of Java you are running. If you build with a 1.4 or 1.5 JDK you
will build a version that supports the JDBC 3 specification and if you build with
a 1.6 or higher JDK you will build a version that supports the JDBC 4 specification.

View File

@ -0,0 +1,70 @@
---
layout: default_docs
title: Configuring the Client
header: Chapter 4. Using SSL
resource: media
previoustitle: Chapter 4. Using SSL
previous: ssl.html
nexttitle: Custom SSLSocketFactory
next: ssl-factory.html
---
Unlike psql and other libpq based programs the JDBC driver does server certificate
validation by default. This means that when establishing a SSL connection the
JDBC driver will validate the server's identity preventing "man in the middle"
attacks. It does this by checking that the server certificate is signed by a
trusted authority. If you have a certificate signed by a global certificate
authority (CA), there is nothing further to do because Java comes with copies of
the most common CA's certificates. If you are dealing with a self-signed certificate
though, you need to make this available to the Java client to enable it to validate
the server's certificate.
> ### Note
> Only the JDBC 3 driver supports SSL. The 1.4 JDK was the first version to come
bundled with SSL support. Previous JDK versions that wanted to use SSL could
make use of the additional JSSE library, but it does not support the full range
of features utilized by the PostgreSQL™ JDBC driver.
To make the server certificate available to Java, the first step is to convert
it to a form Java understands.
`openssl x509 -in server.crt -out server.crt.der -outform der`
From here the easiest thing to do is import this certificate into Java's system
truststore.
`keytool -keystore $JAVA_HOME/lib/security/cacerts -alias postgresql -import -file server.crt.der`
The default password for the cacerts keystore is `changeit`. The alias to postgesql
is not important and you may select any name you desire.
If you do not have access to the system cacerts truststore you can create your
own truststore.
`keytool -keystore mystore -alias postgresql -import -file server.crt.der.`
When starting your Java application you must specify this keystore and password
to use.
`java -Djavax.net.ssl.trustStore=mystore -Djavax.net.ssl.trustStorePassword=mypassword com.mycompany.MyApp`
In the event of problems extra debugging information is available by adding
`-Djavax.net.debug=ssl` to your command line.
To instruct the JDBC driver to try and establish a SSL connection you must add
the connection URL parameter `ssl=true`.
<a name="nonvalidating"></a>
## Using SSL without Certificate Validation
In some situations it may not be possible to configure your Java environment to
make the server certificate available, for example in an applet. For a large
scale deployment it would be best to get a certificate signed by recognized
certificate authority, but that is not always an option. The JDBC driver provides
an option to establish a SSL connection without doing any validation, but please
understand the risk involved before enabling this option.
A non-validating connection is established via a custom `SSLSocketFactory` class
that is provided with the driver. Setting the connection URL parameter `sslfactory=org.postgresql.ssl.NonValidatingFactory`
will turn off all SSL validation.

View File

@ -0,0 +1,29 @@
---
layout: default_docs
title: Custom SSLSocketFactory
header: Chapter 4. Using SSL
resource: media
previoustitle: Configuring the Client
previous: ssl-client.html
nexttitle: Chapter 5. Issuing a Query and Processing the Result
next: query.html
---
PostgreSQL™ provides a way for developers to customize how a SSL connection is
established. This may be used to provide a custom certificate source or other
extensions by allowing the developer to create their own `SSLContext` instance.
The connection URL parameters `sslfactory` and `sslfactoryarg` allow the user
to specify which custom class to use for creating the `SSLSocketFactory`. The
class name specified by `sslfactory` must extend `javax.net.ssl.SSLSocketFactory`
and be available to the driver's classloader. This class must have a zero argument
constructor or a single argument constructor taking a String argument. This
argument may optionally be supplied by `sslfactoryarg`.
Information on how to actually implement such a class is beyond the scope of this
documentation. Places to look for help are the [JSSE Reference Guide](https://docs.oracle.com/javase/8/docs/technotes/guides/security/jsse/JSSERefGuide.html)
and the source to the `NonValidatingFactory` provided by the JDBC driver.
The Java SSL API is not very well known to the JDBC driver developers and we
would be interested in any interesting and generally useful extensions that you
have implemented using this mechanism. Specifically it would be nice to be able
to provide client certificates to be validated by the server.

View File

@ -0,0 +1,37 @@
---
layout: default_docs
title: Chapter 4. Using SSL
header: Chapter 4. Using SSL
resource: media
previoustitle: Connecting to the Database
previous: connect.html
nexttitle: Configuring the Client
next: ssl-client.html
---
**Table of Contents**
* [Configuring the Server](ssl.html#ssl-server)
* [Configuring the Client](ssl-client.html)
* [Using SSL without Certificate Validation](ssl-client.html#nonvalidating)
* [Custom SSLSocketFactory](ssl-factory.html)
<a name="ssl-server"></a>
# Configuring the Server
Configuring the PostgreSQL™ server for SSL is covered in the [main
documentation](http://www.postgresql.org/docs/current/static/ssl-tcp.html),
so it will not be repeated here. Before trying to access your SSL enabled
server from Java, make sure you can get to it via **psql**. You should
see output like the following if you have established a SSL connnection.
`$ ./bin/psql -h localhost`
`Welcome to psql 8.0.0rc5, the PostgreSQL interactive terminal.`
`Type: \copyright for distribution terms`
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`\h for help with SQL commands`
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`\? for help with psql commands`
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`\g or terminate with semicolon to execute query`
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;`\q to quit`
`SSL connection (cipher: DHE-RSA-AES256-SHA, bits: 256)`

View File

@ -0,0 +1,25 @@
---
layout: default_docs
title: Using the Statement or PreparedStatement Interface
header: Chapter 5. Issuing a Query and Processing the Result
resource: media
previoustitle: Chapter 5. Issuing a Query and Processing the Result
previous: query.html
nexttitle: Using the ResultSet Interface
next: resultset.html
---
The following must be considered when using the `Statement` or `PreparedStatement`
interface:
* You can use a single `Statement` instance as many times as you want. You could
create one as soon as you open the connection and use it for the connection's
lifetime. But you have to remember that only one `ResultSet` can exist
per `Statement` or `PreparedStatement` at a given time.
* If you need to perform a query while processing a `ResultSet`, you can simply
create and use another `Statement`.
* If you are using threads, and several are using the database, you must use a
separate `Statement` for each thread. Refer to [Chapter 10, *Using the Driver in a Multithreaded or a Servlet Environment*](thread.html)
if you are thinking of using threads, as it covers some important points.
* When you are done using the `Statement` or `PreparedStatement` you should close
it.

View File

@ -0,0 +1,38 @@
---
layout: default_docs
title: Chapter 10. Using the Driver in a Multithreaded or a Servlet Environment
header: Chapter 10. Using the Driver in a Multithreaded or a Servlet Environment
resource: media
previoustitle: Server Prepared Statements
previous: server-prepare.html
nexttitle: Chapter 11. Connection Pools and Data Sources
next: datasource.html
---
A problem with many JDBC drivers is that only one thread can use a `Connection`
at any one time --- otherwise a thread could send a query while another one is
receiving results, and this could cause severe confusion.
The PostgreSQL™ JDBC driver is thread safe. Consequently, if your application
uses multiple threads then you do not have to worry about complex algorithms to
ensure that only one thread uses the database at a time.
If a thread attempts to use the connection while another one is using it, it
will wait until the other thread has finished its current operation. If the
operation is a regular SQL statement, then the operation consists of sending the
statement and retrieving any `ResultSet` (in full). If it is a fast-path call
(e.g., reading a block from a large object) then it consists of sending and
retrieving the respective data.
This is fine for applications and applets but can cause a performance problem
with servlets. If you have several threads performing queries then each but one
will pause. To solve this, you are advised to create a pool of connections. When
ever a thread needs to use the database, it asks a manager class for a `Connection`
object. The manager hands a free connection to the thread and marks it as busy.
If a free connection is not available, it opens one. Once the thread has
finished using the connection, it returns it to the manager which can then either
close it or add it to the pool. The manager would also check that the connection
is still alive and remove it from the pool if it is dead. The down side of a
connection pool is that it increases the load on the server because a new session
is created for each `Connection` object. It is up to you and your applications's
requirements.

View File

@ -0,0 +1,121 @@
---
layout: default_docs
title: Tomcat setup
header: Chapter 11. Connection Pools and Data Sources
resource: media
previoustitle: Applications DataSource
previous: ds-ds.html
nexttitle: Data Sources and JNDI
next: jndi.html
---
### Note
The postgresql.jar file must be placed in $CATALINA_HOME/common/lib in both
Tomcat 4 and 5.
The absolute easiest way to set this up in either tomcat instance is to use the
admin web application that comes with Tomcat, simply add the datasource to the
context you want to use it in.
Setup for Tomcat 4 place the following inside the &lt;Context&gt; tag inside
conf/server.xml
<pre><code>
&lt;Resource name="jdbc/postgres" scope="Shareable" type="javax.sql.DataSource"/&gt;
&lt;ResourceParams name="jdbc/postgres"&gt;
&lt;parameter&gt;
&lt;name&gt;validationQuery&lt;/name&gt;
&lt;value&gt;select version();&lt;/value&gt;
&lt;/parameter&gt;
&lt;parameter&gt;
&lt;name&gt;url&lt;/name&gt;
&lt;value&gt;jdbc:postgresql://localhost/davec&lt;/value&gt;
&lt;/parameter&gt;
&lt;parameter&gt;
&lt;name&gt;password&lt;/name&gt;
&lt;value&gt;davec&lt;/value&gt;
&lt;/parameter&gt;
&lt;parameter&gt;
&lt;name&gt;maxActive&lt;/name&gt;
&lt;value&gt;4&lt;/value&gt;
&lt;/parameter&gt;
&lt;parameter&gt;
&lt;name&gt;maxWait&lt;/name&gt;
&lt;value&gt;5000&lt;/value&gt;
&lt;/parameter&gt;
&lt;parameter&gt;
&lt;name&gt;driverClassName&lt;/name&gt;
&lt;value&gt;org.postgresql.Driver&lt;/value&gt;
&lt;/parameter&gt;
&lt;parameter&gt;
&lt;name&gt;username&lt;/name&gt;
&lt;value&gt;davec&lt;/value&gt;
&lt;/parameter&gt;
&lt;parameter&gt;
&lt;name&gt;maxIdle&lt;/name&gt;
&lt;value&gt;2&lt;/value&gt;
&lt;/parameter&gt;
&lt;/ResourceParams&gt;
</code></pre>
Setup for Tomcat 5, you can use the above method, except that it goes inside the
&lt;DefaultContext&gt; tag inside the &lt;Host&gt; tag. eg. &lt;Host&gt; ... &lt;DefaultContext&gt; ...
Alternatively there is a conf/Catalina/hostname/context.xml file. For example
http://localhost:8080/servlet-example has a directory $CATALINA_HOME/conf/Catalina/localhost/servlet-example.xml file.
Inside this file place the above xml inside the &lt;Context&gt; tag
Then you can use the following code to access the connection.
<pre><code>
import javax.naming.*;
import javax.sql.*;
import java.sql.*;
public class DBTest
{
String foo = "Not Connected";
int bar = -1;
public void init()
{
try
{
Context ctx = new InitialContext();
if(ctx == null )
throw new Exception("Boom - No Context");
// /jdbc/postgres is the name of the resource above
DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/postgres");
if (ds != null)
{
Connection conn = ds.getConnection();
if(conn != null)
{
foo = "Got Connection "+conn.toString();
Statement stmt = conn.createStatement();
ResultSet rst = stmt.executeQuery("select id, foo, bar from testdata");
if(rst.next())
{
foo=rst.getString(2);
bar=rst.getInt(3);
}
conn.close();
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
public String getFoo() { return foo; }
public int getBar() { return bar;}
}
</code></pre>

View File

@ -0,0 +1,30 @@
---
layout: default_docs
title: Performing Updates
header: Chapter 5. Issuing a Query and Processing the Result
resource: media
previoustitle: Using the ResultSet Interface
previous: resultset.html
nexttitle: Creating and Modifying Database Objects
next: ddl.html
---
To change data (perform an `INSERT`, `UPDATE`, or `DELETE`) you use the
`executeUpdate()` method. This method is similar to the method `executeQuery()`
used to issue a `SELECT` statement, but it doesn't return a `ResultSet`; instead
it returns the number of rows affected by the `INSERT`, `UPDATE`, or `DELETE`
statement. [Example 5.3, “Deleting Rows in JDBC”](update.html#delete-example)
illustrates the usage.
<a name="delete-example"></a>
**Example 5.3. Deleting Rows in JDBC**
This example will issue a simple `DELETE` statement and print out the number of
rows deleted.
`int foovalue = 500;`
`PreparedStatement st = conn.prepareStatement("DELETE FROM mytable WHERE columnfoo = ?");`
`st.setInt(1, foovalue);`
`int rowsDeleted = st.executeUpdate();`
`System.out.println(rowsDeleted + " rows deleted");`
`st.close();`

View File

@ -0,0 +1,32 @@
---
layout: default_docs
title: Chapter 3. Initializing the Driver
header: Chapter 3. Initializing the Driver
resource: media
previoustitle: Creating a Database
previous: your-database.html
nexttitle: Chapter 3. Loading the Driver
next: load.html
---
**Table of Contents**
* [Importing JDBC](use.html#import)
* [Loading the Driver](load.html)
* [Connecting to the Databas](connect.html)
* [Connection Parameters](connect.html#connection-parameters)
This section describes how to load and initialize the JDBC driver in your programs.
<a name="import"></a>
# Importing JDBC
Any source that uses JDBC needs to import the `java.sql` package, using:
import java.sql.*;
### Note
You should not import the `org.postgresql` package unless you are not using standard
PostgreSQL™ extensions to the JDBC API.

View File

@ -0,0 +1,20 @@
---
layout: default_docs
title: Creating a Database
header: Chapter 2. Setting up the JDBC Driver
resource: media
previoustitle: Preparing the Database Server for JDBC
previous: prepare.html
nexttitle: Chapter 3. Initializing the Driver
next: use.html
---
When creating a database to be accessed via JDBC it is important to select an
appropriate encoding for your data. Many other client interfaces do not care
what data you send back and forth, and will allow you to do inappropriate things,
but Java makes sure that your data is correctly encoded. Do not use a database
that uses the `SQL_ASCII` encoding. This is not a real encoding and you will
have problems the moment you store data in it that does not fit in the seven
bit ASCII character set. If you do not know what your encoding will be or are
otherwise unsure about what you will be storing the `UNICODE` encoding is a
reasonable default to use.