我在我的Java应用程序中创建了一个getDBConnection方法。这将返回一个连接对象,因此我没有在这个方法本身中关闭这个连接。JDBC连接问题
现在,我定期从我的应用程序中的各种方法调用此方法,并在try - finally块内关闭它们。我认为这应该在使用后释放连接。但是,我看到MySQL管理员的服务器连接选项卡中打开了大量连接(大约50个)。
//Defining a method to retrieve a database connection
// PropDemo is a properties class that retrieves Database related values from a file
public Connection getDBConnection() {
//Instantiating the Properties object
PropDemo prop = new PropDemo();
Connection con = null;
// Retrieving values from the parameters.properties file
String JdbcDriver = prop.getMessage("JdbcDriver");
String JdbcUrlPrefix = prop.getMessage("JdbcUrlPrefix");
String DBIP = prop.getMessage("DBIP");
String DBName = prop.getMessage("DBName");
String DBUser = prop.getMessage("DBUser");
String DBPassword = prop.getMessage("DBPassword");
try {
// Loading and instantiating the JDBC MySQL connector driver class
Class.forName(JdbcDriver).newInstance();
con = DriverManager.getConnection(JdbcUrlPrefix + DBIP + "/" + DBName, DBUser, DBPassword);
if (con.isClosed())
Logger.log("Connection cannot be established", "vm");
} catch (Exception e) {
Logger.log("Exception: " + e, "vm");
Logger.log(Logger.stack2string(e), "vm");
}
return con;
}
我也关闭了相关的ResultSet和Statement对象。这里可能会丢失什么?
出于效率和安全原因,我计划用PreparedStatements替换所有语句。这会有帮助吗?还有什么可以做的?
编辑: 这只是一个核心的Java应用程序,通过MySQL-JDBC连接器反复查询MySQL数据库中某些字段的更改。我没有使用像Spring或Hibernate这样的框架。
你可以发布您的代码? – Mark 2009-01-28 01:00:16
需要更多信息。你的环境是什么,它是一个独立的应用程序框架,一个JavaEE容器?你使用连接池吗? – OscarRyz 2009-01-28 01:22:07