Oracle Exams Establish a Database Connection,Exams of Oracle,Oracle Certification Exam Getting Connected – JDBC Applications and Design Considerations

Getting Connected – JDBC Applications and Design Considerations



4.2.2   Getting Connected

To establish a connection to the desired database, two methods can be used:

  1. Using DriverManager.getConnection()
  2. Using Driver.connect()

Before we can take a closer look at these two methods, first let’s have a quick review of all methods defined in these two classes, DriverManager and Driver.

4.2.2.1   The DriverManager and Driver Classes

All 12 methods defined in the DriverManager class are shown in Table 4.1.

Four methods in the DriverManager class are widely applied in most database applications: getConnection(), getDriver(), registerDriver() and deregisterDriver(). Note that the getConnection() method has two more overloaded methods with different arguments.

All six methods defined in the Driver class are shown in Table 4.2.

The most popular methods in the Driver class are acceptsURL() and connect().

Most methods defined in the Driver class will not be called directly in most Java database appli-cations; instead, they will be called indirectly by using the DriverManager class.

Now let’s have a closer look at these two methods.

4.2.2.2   Using the DriverManager.getConnection() Method When using the first method, DriverManager.getConnection(), to establish a database connection, it does not immediately try to make this connection. Instead, in order to make this con-nection more robust, it performs a two-step process. The getConnection() method first checks the driver and uniform resource locator (URL) by running a method called acceptsURL() via the DriverManager class to test the first driver in the driver list. If no matching driver returns, the acceptURL() method will go to test the next driver in the list. This process continues until each driver is tested or a matchingdriver is found. If a matching driver is found, the Driver.con-nect() method will be executed to establish this connection. Otherwise, an exception is raised.

If it looks like this two-step connection is not efficient enough, a more robust connection can be set if more than one driver is available in the driver list.

The purpose of the acceptsURL() method is to check whether the current driver is able to open a valid connection to the given URL. This method does not create a real connection or test the actual database connections; instead, it merely examines the sub-protocol of the URL and deter-mines if it understands its syntax. In this way, it can effectively reduce the chance of a misconnec-tion and make sure of the correctness of an established connection.

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Post