Reputation: 493
I'm still pretty new to Java and was playing around with the GUI builder to learn some of Java's OO and other programming concepts.
I created a very basic banking system where customer can deposit money and withdraw money, basically.
I don't particularly have a problem with my code as everything works, I just have a problem about database connections.
Since the code to create a connection is always repeated, I created a database class such as below:
public class DB {
static Connection c;
public static void createConnection() throws Exception{
Class.forName("com.mysql.jdbc.Driver");
DB.c = DriverManager.getConnection("jdbc:mysql://localhost:3306/bank", "root", "");
}
public static int insertUpdateDelete(String sql) throws Exception{
if(c == null){
createConnection();
}
return c.createStatement().executeUpdate(sql);
}
public static ResultSet search(String sql) throws Exception{
if(c == null)
createConnection();
return c.createStatement().executeQuery(sql);
}
}
So whenever I want to insert/update/delete from a database I just did:
DB.insertUpdateDelete(SQL); //SQL contains the query
And for search I'd do:
ResultSet rs = DB.search(SQL);
After a bit of reading, I learnt that having static connection objects aren't the best practice due to "resource leaking" and queries interfering with each other.
My question is, what is the best way to get the connection in a standalone Java application where one does not have to keep repeating the same code over and over again.
Thank you
Upvotes: 4
Views: 1386
Reputation: 40894
The normal approach is a connection pool.
A static connection object has problems:
Opening a connection every time is just slow.
A connection pool keeps a reasonable number of open connections, knows how to replace those that get disconnected due to an error, and can give you a connection, and take it back, very quickly.
There are several implementations of connection pools for JDBC.
Upvotes: 6