sharing a JDBC Connection object between other objects

Mus*_*aie 5 java connection jdbc

I have created a Database class which uses a static connection object in order to be used in common between instances of itself. my question is that is there any problem with this approach or not?

class Database {
    private static Connection connection = null;

    public Database() {
        if(connection == null){
            ...
            connection = DriverManager.getConnection(...);
            ...
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Ove*_*ave 4

如果每秒有许多(数百)个查询,那么实现连接池是最佳选择。有关更多详细信息,请参阅问题的答案。然而,如果您是一名 Java 新手(我们都曾经是这样的!)那么我不认为您会需要这个要求,并且可能会很难实现它。

相反,如果需要,创建新连接,然后在完成后关闭它的简单模式将是您前进的最佳方式。下面是您的课程的修改版本Database,我认为这是前进的好方法。

class Database {
    private Connection con = null;
    private final String connectionString;

    public Database(String connectionString) {
        this.connectionString = connectionString;
    }

    public void connect() throws SQLException {
        if (con != null // if the connection exists
             && !con.isClosed() // and has not been closed 
             && con.isValid(0)) { // and appears to be functioning (with a test timeout of 0ms)
             return; // skip connection creation
        }

        // create the connection
        con = DriverManager.getConnection(connectionString);        
    }

    public void testFunction() {
        try {
            connect();
            // .. do some stuff with the connection ..
        } catch (Exception e) {
            // log or otherwise deal with the error
        } finally {
            try {
                con.close();
            } catch (Exception e) {
                System.err.println("Failed to close connection: " + e.toString());
            }
        }

    }
}
Run Code Online (Sandbox Code Playgroud)

关于此解决方案需要注意的一些事项:

  • 它不是高效 - 创建新连接总是比使用现有连接花费更多时间
  • 此类如果不是线程安全的 - 如果您需要此要求,我建议使用线程池。但是,如果您为每个线程创建此类的新实例,那么它将线程安全的(因为无需担心静态连接!)
  • 它确实可以完成工作——当然对于简单的情况来说。我将该模型用于相对较小容量的数据库,该数据库每分钟大约建立/关闭 50-100 个连接,并且不会增加明显的延迟
  • 非常强大 - 没有什么比每个查询打开和关闭连接更安全的了。您保证能够处理每个查询的连接失败,并且连接将始终关闭(除非它已经关闭)。

免责声明上面的解决方案并不是一个特别令人惊奇的解决方案。不过,我相信它实现起来很简单,对于 Java 新手来说,这是在进入外部库之前了解情况的好方法。