Java Reference
In-Depth Information
ager to obtain a connection to the database. As of JDBC version 4.0, drivers that are
contained within the CLASSPATH are automatically loaded into the DriverMan-
ager object. If you are using a JDBC version prior to 4.0, the driver will have to be
manually loaded.
To obtain a connection to your database using the DriverManager , you need to
pass a string containing the JDBC URL to it. The JDBC URL consists of the database
vendor name, along with the name of the server that hosts the database, the name of the
database, the database port number, and a valid database username and password that
has access to the schema that you want to work with. Many times, the values used to
create the JDBC URL are obtained from a Properties file so that they can be easily
changed if needed. To learn more about using a Properties file to store connection
values, see Recipe 13-5. The code that is used to create the Oracle database JDBC URL
for Solution 1 looks like the following:
String jdbcUrl = "jdbc:oracle:thin:@" + this.hostname
+ ":" +
this.port + ":" + this.database;
Once all the variables have been substituted into the string, it will look something
like the following:
jdbc:oracle:thin:@hostname:1521:database
Similarly, the Apache Derby URL string would look like the following:
jdbc:derby://hostname:1521/database
Once the JDBC URL has been created, it can be passed to the DriverMan-
ager.getConnection() method to obtain a java.sql.Connection object.
If incorrect information has been passed to the getConnection() method, a
java.sql.SQLException will be thrown; otherwise, a valid Connection ob-
ject will be returned.
The preferred way to obtain a database connection is to use a DataSource when
running on an application server or to have access to a Java Naming and Directory In-
terface (JNDI) service. To work with a DataSource object, you need to have an ap-
plication server deploy it to. Any compliant Java application server such as Glassfish,
Oracle Weblogic, or WildFly will work. Most of the application servers contain a web
interface that can be used to easily deploy a DataSource object. However, you can
Search WWH ::




Custom Search