Using the Driver Interface and DriverManager Class

Một phần của tài liệu Beginning Databases with Postgre SQL phần 8 ppt (Trang 55 - 60)

The java.sql package defines an interface called java.sql.Driver, which needs to be imple- mented by all the JDBC drivers, and a class called java.sql.DriverManager, which acts as the interface to the database. The primary task of the DriverManager class is to manage the various

registered JDBC drivers. The DriverManager also provides methods for getting connections to databases, managing JDBC logs, and setting the login timeout. When a JDBC client requests the DriverManager to make a connection to an external resource manager, it delegates the task to an appropriate driver class implemented by the JDBC driver provided either by the resource manager vendor or a third party.

In this section, we will discuss the roles of java.sql.DriverManager and java.sql.Driver in the JDBC API. However, before we discuss the main JDBC functions, we need to briefly mention the way exceptions and warnings are handled.

SQL Exceptions and Warnings

The core JDBC API provides four exception classes, which you may need to catch:

• BatchUpdateException: This exception is thrown when an error occurs during the execution of a SQL batch. The class gives a method to get the update counts of the SQL statements that were executed successfully in the batch as an array of integers.

• DataTruncation: This exception is thrown when the data is unexpectedly truncated during data reads or writes. The class provides methods to access the number of bytes that should have been transferred and those actually transferred, whether the truncation occurred for a column or a parameter, whether the truncation occurred on a read or a write, and the index of the column or the parameter.

• SQLException: This is the superclass of all the other SQL exceptions. This class provides access methods for the database error code and SQL state for the error that caused this exception. Most of the methods discussed in this chapter will throw an instance of SQLException if a database-access error occurs (as you’ll notice from their signatures).

• SQLWarning: This subclass of SQLException is thrown to indicate warnings during database access.

Managing Drivers

The DriverManager class provides the following methods for managing drivers:

• public static void registerDriver(Driver driver) throws SQLException: The registerDriver method is normally used by the implementation classes of the java.sql.Driver interface, provided by the JDBC drivers, to register themselves with the DriverManager. DriverManager uses registered drivers for delegating database connection requests.

• public static void deregisterDriver(Driver driver) throws SQLException: The deregisterDriver method is used for deregistering a driver that is already registered with the DriverManager.

• public static Enumeration getDrivers(): The getDrivers method returns an enumer- ation of all the drivers currently registered with the DriverManager. The signature shown here is for Java Development Kit (JDK) 1.4 and earlier versions. In JDK 1.5, the signature changes to public Enumeration<Driver> getDrivers().

• public static Driver getDriver(String url) throws SQLException: The getDriver method locates a driver corresponding to the passed JDBC URL.

Specifying the Server and Database

JDBC URLs are used for uniquely identifying the resource manager type and resource manager location. This means that even though a JDBC driver can handle any number of connections identified by different JDBC URLs, the basic URL format, including the protocol and subpro- tocol, is specific to the driver used.

JDBC clients specify the JDBC URL when they request a connection. The DriverManager can find a driver that matches the requested URL from the list of registered drivers and delegate the connection request to that driver if it finds a match.

JDBC URLs take the following format:

<protocol>:<subprotocol>:<resource>

The protocol is always jdbc, but the subprotocol and resource depend on the type of resource manager you use. The URL for PostgreSQL has this format:

jdbc:postgresql://<host>:<port>/<database>

Here, host is the host address (either an IP address or a machine name) on which the PostgreSQL server process is accepting connections, and database is the name of the database to which the client wishes to connect. The port parameter is optional, and it is required only if your PostgreSQL service is listening on a port other than the default 5432.

As an example, if we wish to connect to the database bpfinal on the machine at IP address 192.168.0.3 using the default port, we would use the following URL in our Java code:

String url = "jdbc:postgresql://192.168.0.3/bpfinal";

Managing Connections

The DriverManager class provides the getConnection method for managing connections to databases. This method has three alternative signatures:

• public static Connection getConnection(String url) throws SQLException: The getConnection method creates a connection to the database specified by the JDBC URL.

The class java.sql.Connection is covered in detail in the “Making Database Connections”

section later in this chapter.

• public static Connection getConnection(String url,String user,String password) throws SQLException: This form of the getConnection method gets a connection to the database specified by the JDBC URL using the specified username and password.

• public static Connection getConnection(String url,Properties info) throws SQLException: This form of the getConnection method gets a connection to the database specified by the JDBC URL, and the instance of the class java.util.Properties is used for specifying the security credentials. The user property is used for specifying the user- name, and the password property is used for specifying the password.

Managing JDBC Logging

The DriverManager class provides the following methods for managing JDBC logs:

• public static PrintWriter getLogWriter(): The PrintWriter method gets a handle to an instance of the class java.io.PrintWriter to which the logging and tracing informa- tion are written.

• public static void setLogWriter(PrintWriter writer): The setLogWriter method sets the PrintWriter class to which all the log information is written by the DriverManager and all the registered drivers.

• public static void println(String message) throws SQLException: This println method writes the message to the current log stream.

Managing Login Timeouts

Two methods are provided by the DriverManager class for managing logins:

• public static int getLoginTimeout(): The getLoginTimeout method gets the maximum time in seconds the DriverManager would wait for getting a connection.

• public static void setLoginTimeout(int seconds): The setLoginTimeout method sets the maximum time, in seconds, the DriverManager would wait for getting a connection.

Implementing java.sql.Driver

The java.sql.Driver interface defines the methods that need to be implemented by all JDBC driver classes. The driver implementation classes are required to have static initialization code to register them with the current DriverManager. This is done so that the DriverManager has the driver in the list of registered drivers, and it delegates a connection request to an appropriate driver class depending on the JDBC URL specified. The curious can take a look at the source code for the org.postgresql.Driver class, which is the driver implementation for the PostgreSQL JDBC driver.

One obvious way of checking that you have a driver available is using the static forName() method on the class java.lang.Class:

try {

Class.forName("org.postgresql.Driver");

} catch(ClassNotFoundException e) { // Handle exception

}

This will throw a ClassNotFoundException if the class org.postgresql.Driver is not found in the CLASSPATH. So, you need to make sure that the postgres.jar file that contains the required classes is available in the CLASSPATH, as we mentioned previously.

The sequence diagram shown in Figure 17-2 depicts a typical JDBC client getting a connection to a PostgreSQL database running locally, using the username meeraj and the password waheeda.

Figure 17-2. Connection sequence

The following code snippet corresponds to the sequence of events depicted in Figure 17-2, assuming a database named test on the local machine:

try {

// Load the JDBC driver

Class.forName("org.postgresql.Driver");

// Create a properties object with username and password Properties prop = new Properties();

prop.setProperty("user", "meeraj");

prop.setProperty("password", "waheeda");

// Set the JDBC URL

String url = "jdbc:postgresql:test";

// Get the connection

Connection con = DriverManager.getConnection(url, prop);

} catch(ClassNotFoundException e) { // Handle exception

} catch(SQLException e) { // Handle exception }

jdbcClient

Class.for Name("org.postgosql.Driver")

setProperty("user","meeraj") setProperty("password","Wahcoda")

getConnection("ldbc:postgpsql:test",prop):java.sql.Connection

java.lang.Class java.sql.DriverManager

PROP Properties

The following methods are defined for the java.sql.Driver interface:

• public boolean acceptsURL(String url) throws SQLException: The acceptsURL method returns True if the driver implementation class can open a connection to the specified URL. The implementation classes normally return True if they can recognize the subprotocol specified in the JDBC URL.

• public Connection connect(String url,Properties info) throws SQLException: The connect method returns a connection to the specified URL using the properties defined in the argument info. The DriverManager normally calls this method when it receives connection requests from JDBC clients.

• public int getMajorVersion(): The getMajorVersion method returns the major revision number of the driver.

• public int getMinorVersion(): The getMinorVersion method returns the minor revision number of the driver.

• public boolean jdbcCompliant(): The jdbcCompliant method returns True if the driver is JDBC-compliant. A fully compliant JDBC driver should conform strictly to the JDBC API and at least the SQL92 Entry Level specifications.

Making Database Connections

The java.sql.Connection interface defines the methods required for a persistent connection to the database. The JDBC driver vendor implements this interface. A vendor-neutral database client will always use only the interface, not the implementation class.

JDBC clients use statements, prepared statements, and callable statements for issuing SQL statements to the database. Statements generally are used for the following tasks:

• Getting and setting auto-commit mode

• Getting meta information about the database

• Committing and rolling back transactions

In this section, we will cover the various methods defined in the java.sql.Connection interface. We will discuss statements in more detail in the “Using JDBC Statements” section later in this chapter.

Một phần của tài liệu Beginning Databases with Postgre SQL phần 8 ppt (Trang 55 - 60)

Tải bản đầy đủ (PDF)

(66 trang)