I'm currently writing an application and I'm struggling with the decision of how to correctly design a class to connect to a database. I came up with something like this:
public class DatabaseConnector {
private Connection databaseConnection = null;
public DatabaseConnector(String url, String user, String password) {
databaseConnection = DriverManager.getConnection(url, user, password);
}
public void close() throws SQLException {
databaseConnection.close();
}
}
Additionally, in this class I have methods to pull something from database or insert and so on, and for each method a create a separate PrepareStatement
and ResultSet
and other objects.
My question is if this approach is correct, somehow wrong, or terribly wrong. I will be glad for every tip on designing a good communication class and how to correctly work with databases.
I use a MySQL database and JDBC for communication.
Best Answer
I prefer a two-classes design in connecting to a database. This approach is especially efficient in communicating with multiple databases within a single application:
To be more specific, for instance, the select method in CommDB looks something like this:
and a specific code for getting user info from MyDB may look like: