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)
如果每秒有许多(数百)个查询,那么实现连接池是最佳选择。有关更多详细信息,请参阅此问题的答案。然而,如果您是一名 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)
关于此解决方案需要注意的一些事项:
免责声明上面的解决方案并不是一个特别令人惊奇的解决方案。不过,我相信它实现起来很简单,对于 Java 新手来说,这是在进入外部库之前了解情况的好方法。
| 归档时间: |
|
| 查看次数: |
3999 次 |
| 最近记录: |