简体   繁体   中英

Disadvantages of static Connection object in Java standalone application

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

The normal approach is a connection pool.

A static connection object has problems:

  • You keep a connection per user session. With many users, it noticeably increases the load on the DB server (or your license costs if any).
  • If a connection dies or times out, you have no way to re-establish it.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM