In order to interact with the database, it is necessary to install the correct driver, and to open a connection to the database.
The first step before writing the source code is to install a version of the JDBC PostgreSQL driver that is compatible with both: the used JDK version and the version of the database server.
The webpage at the hyperlink http://jdbc.postgresql.org/download.html shows the driver that is compatible with the used versions of PostgreSQL and JDK.
The driver can either be downloaded as a .jar
file, and then manually added to the class-path. Or, if a build tool like Maven or Gradle is used, it can be downloaded and installed automatically by adding the resource to the build-script accordingly. A link to the Maven Repository where the resource definitions can be looked up is provided on the driver download page.
Before connecting to a database, the JDBC driver must be loaded and initialized.
Prior to JDBC 4.0, it was necessary to load the driver class by calling Class.forName("org.postgresql.Driver")
once before using it. This loads the driver into memory, and it registers itself with JDBC.
Since JDBC 4.0, it is also possible to pass the JDBC driver class as an argument to the JVM when the application is started:
java -Djdbc.drivers=org.postgresql.Driver carportal.MainClass
This causes the JVM to load the driver during its initialization process, and provides an even more flexible method to use the existing code with different JDBC implementations.
A Java class that uses JDBC needs to import the java.sql
package:
import java.sql.*;
It should not use the packages from the org.postgresql
package unless the PostgreSQL extensions to the JDBC are used. This keeps the code portable to other database vendors.
After importing the java.sql
package, a connection to a database can be obtained from the DriverManager
class by calling one of its getConnection
methods:
DriverManager.getConnection(String url)
DriverManager.getConnection(String url, String username, String password)
DriverManager.getConnection(String url, Properties properties)
All three methods return a java.sql.Connection
object, which can subsequently be used to interact with the database.
The parameter url
in all these methods specifies how the driver will connect to the database, and can be in one of these formats:
jdbc:postgresql:<databaseName>
jdbc:postgresql://<host>/<databaseName>
jdbc:postgresql://<host>:<port>/<databaseName>
Using a URL without a host and port will create a connection to a PostgreSQL server running on the local computer (localhost) and listening on the PostgreSQL standard port (5432
).
If the database server runs on a remote host or uses a non-standard port number, these parameters have to be added to the connection URL. The host can be given either as the host name or the IP address.
The IPv6 addresses must be enclosed in square brackets:
jdbc:postgresql://[::1]:5432/carportal
If the database server requires additional parameters to be set when opening a connection, these can be specified by using the last two getConnection
methods listed earlier. The most common case will be that a database requires a username and password.
Other parameters might be setting the protocol version or enabling the SSL support. These parameters can be passed as name/value pairs stored in a java.util.Properties
object.
A complete list of connection parameters can be found in the documentation of the JDBC driver. For the PostgreSQL driver version used in this chapter, the documentation can be found at http://jdbc.postgresql.org/documentation/93/connect.html#connection-parameters.
After usage, the connection should be closed again to free the resources:
Connection connection = null; String url = "jdbc:postgresql:carportal"; try{ connection = DriverManager.getConnection(url); } finally{ if(connection!=null){ connection.close(); } }
Since the Connection
interface extends java.lang.AutoCloseable
, using a try-with-resources block is a more convenient way of closing the connection after usage:
String url = "jdbc:postgresql:carportal"; try(Connection connection = DriverManager.getConnection(url)) { // use the connection here }
Now the JVM will automatically close the connection when the try-block is exited.
Most methods that interact with a database can throw an SQLException
. The SQLException
interface defines the following methods to retrieve the details about the cause of the error that has occurred:
String getMessage()
: This returns a textual description of the error.String getSQLState()
: This returns a five-character long alphanumeric code.int getErrorCode()
: This may return a vendor-specific error code if implemented by the driver. In most cases, this will be the error code returned by the database server.Throwable getCause()
: If SQLException
was caused by an instance of throwable being thrown, then throwable is returned.SQLException getNextException()
: If more than one error occurred, the associated SQLExceptions
can be iterated by sequentially calling this method until null is returned.
SQLWarnings
is a subclass of SQLException
that provides information about the database access warnings.
SQLWarnings
are not thrown, but can be retrieved by calling the getWarnings
method on objects of the types Connection
, Statement
, or ResultSet
. If more than one warning was raised, they can be iterated the same same way as SQLException
by calling the getNextWarning
method on the SQLWarnings
objects.
Upon execution of a statement, all the present warnings will be cleared.
18.118.200.95