I am building DB class, in the constructor I want to establish the connection with database, so that static dbLink is accessible by the rest of the functions inside that class. Is that a good approach?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
As to the concrete question, surely it’s legal to throw exceptions in a constructor. There’s no other sane way to prevent the "DB class" instance from being used with a broken connection.
As to the concrete functional requirement, you’ve another major problem. You should not be creating a DB connection in the constructor of a "DB class" and surely not make it
static. This indicates that you’re intending to keep the connection open as long as the instance of the "DB class" lives in Java’s memory. This is in turn a very bad idea. The connection should instead be created in the very sametryblock as where you’re executing the SQL query/queries. The connection should also be closed in thefinallyblock of thattryblock. This prevents resource leaking in long term which would otherwise cause your application to crash because the DB server times out the resource because it’s been open for too long, or runs out of resources because too many connections have been opened.See also: