I've written this MySQL database class for my Java application and I'd just like some feedback on it before moving onto making my next class.
The idea here is that I have a simple properties file which stores the hostname, username, password, and database name. I then connect to the database (if possible) and return the Connection.
Although I am not really sure what should happen if the properties file doesn't exist, or the MySQL connection fails, should I return Connection which would be null, throw a new exception, or re-throw the existing exception?
Throwing an exception is probably the best choice when you can't establish a connection in this class. Experiment with how you'd write the client code if this were the case. Then compare it with how you'd write the client code if you returned a null Connection instead. Between throwing a new exception that wraps the SQLException vs. just re-throwing the SQLException or IOException, experiment with how you'd write the client code to handle or propagate those exceptions. In the end, you have to consider how your decision here affects the code that uses this API. To paraphrase JFK (but with less eloquence): Think not only of what you must do in this class, think also of what other classes must do because of this class.
I wouldn't make the Database class responsible for getting the connection properties. Pass the required properties to the getConnection() method. That said, your class is actually unnecessary if you use the DataSource interface, which JDBC has an implementation of.
Knute Snortum wrote:You probably don't need this line, if you have a modern JDBC driver.
Explanation. The Class.forName method was originally needed to force the JVM's classloader to locate, load and activate the JDBC driver class in question. For about 10 years more or less it has been possible to construct JARs with special Manifest directives (in the META-INF) directory that permit the same process to operate automatically. Which is why you don't need Class.forName anymore.
As a more abstract observation, actually manually constructing Connection objects is something that has limited utility in industrial-grade systems these days. Web applications should be using a server-constructed Database Connection Pool, and complex stand-alone applications - especially multi-threaded ones - also often perform better using a Connection Pool. So manual construction is mostly for single-user apps.
When it comes to destroying a civilization, gas chambers cannot hold a candle to echo chambers.
Die Fledermaus does not fear such a tiny ad:
how do I do my own kindle-like thing - without amazon