Java Reference
In-Depth Information
ation to obtain a connection to a database. The following code shows code that you can
use to obtain a database connection via a DataSource object:
public Connection getDSConnection() {
Connection conn = null;
try {
Context ctx = new InitialContext();
DataSource ds = (DataSource)ctx.lookup("jdbc/
myOracleDS");
conn = ds.getConnection();
} catch (NamingException | SQLException ex) {
ex.printStackTrace();
}
return conn;
}
Notice that the only information required in the DataSource implementation is
the name of a valid DataSource object. All the information that is required to obtain
a connection with the database is managed within the application server.
How It Works
There are a couple of different ways to create a connection to a database within a Java
application. How you do so depends on the type of application you are writing. Utiliza-
tion of the DriverManager is often used if an application will be stand-alone or if it
is a desktop application. Web-based and intranet applications commonly rely on the ap-
plication server to provide the connection for the application via a DataSource ob-
ject.
Creating a JDBC connection involves a few steps. First, you need to determine
which database driver you will need. After you've determined which driver you will
need, you download the JAR file containing that driver and place it into your
CLASSPATH . For this recipe, either an Oracle database or Apache Derby connection is
made. Each of the database vendors will provide different JDBC drivers packaged in
JAR files that have different names; consult the documentation for your particular data-
base for more information. Once you have obtained the appropriate JAR file for your
database, include it in your application CLASSPATH . Next, use a JDBC DriverMan-
Search WWH ::




Custom Search