Java Reference
In-Depth Information
} catch (java.sql.SQLException ex) {
System.out.println(ex);
}
This code uses try-with-resources to automatically close the connection
when it is finished performing the database task.
How It Works
Obtaining a connection within a database application can be code-intensive. Moreover,
the process can be prone to error if you retype the code each time you need to obtain a
connection. By encapsulating database connection logic within a single class, you can
reuse the same connection code each time you require a connection to the database.
This increases your productivity, reduces the chances of typing errors, and also en-
hances manageability because if you have to make a change, it can occur in one place
rather than in several different locations.
Creating a strategic connection methodology is beneficial to you and others who
might need to maintain your code in the future. Although data sources are the preferred
technique for managing database connections when using an application server or
JNDI, the solution to this recipe demonstrates the use standard JDBC DriverMan-
ager connections. One of the security implications of using the DriverManager is
that you will need to store the database credentials somewhere for use by the applica-
tion. It is not safe to store those credentials in plain text anywhere, and it is also not
safe to embed them in application code, which might be decompiled at some point in
the future. As seen in the solution, a properties file that on disk is used to store the
database credentials. Assume that this properties file will be encrypted at some point
before deployment to a server, and that the application will be able to handle decryp-
tion.
As seen in the solution, the code reads the database credentials, hostname, database
name, and port number from the properties file. That information is then pieced togeth-
er to form a JDBC URL that can be used by DriverManager to obtain a connection
to the database. Once obtained, that connection can be used anywhere and then closed.
Similarly, if using a DataSource that has been deployed to an application server, the
properties file can be used to store the JNDI connection. That is the only piece of in-
formation that is needed to obtain a connection to the database using the
DataSource . To the developer using the connection class, the only difference
Search WWH ::




Custom Search