Maintaining Portability Using Properties Files
Though our focus is on MySQL, it is good Java programming practice to make your applications completely portable. To most people, portability means that you do not write code that will run on only one platform. In the Java world, however, the word “portable” is a much stronger term. It means no hardware resource dependencies, and that means no database dependencies.
We discussed how the JDBC URL and Driver name are
implementation dependent, but we did not discuss the details of how
to avoid hardcoding them. Because both are simple strings, you can
pass them on the command line as runtime arguments or as parameters
to applets. While that solution works, it is hardly elegant since it
requires command-line users to remember long command lines. A similar
solution might be to prompt the user for this information; but again,
you are requiring that the user remember a JDBC URL and a Java class
name each time he runs an application.
Properties files
A
more elegant solution than either of
those mentioned would be to use a properties file. Properties files
are supported by the
java.util.ResourceBundle
and its subclasses to enable an
application to extract runtime-specific information from a text file.
For a JDBC application, you can stick the URL and
Driver name in the properties file, leaving the
details of the connectivity up to an application administrator. Example 13-2 shows a properties file that provides
connection information.
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access