我在 GWT 中执行 RPC 来查询数据库,并且我的程序中有内存泄漏,我强烈怀疑它与我设置类的方式有关。目前,我必须在我拥有的每个方法中连接到数据库,然后在方法结束时关闭该连接。这样做会导致内存泄漏吗?我觉得以这种方式编程会导致更多代码并且效率极低,但我找不到很多好的示例可以使用,有人可以建议一种更好的方法吗?名称、IP 已更改,并且我已经发布了 connect 方法以及如何编写其他方法的示例。
public class DatabaseServiceImpl extends RemoteServiceServlet implements DatabaseService {
private Connection con = null;
String database = "ioma";
String host = "localhost";
String password = "foo";
String url = "jdbc:mysql://" + host + "/" + database;
String user = "foo";
public String connect() {
String connect = "";
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
for (Throwable t : e)
System.err.println("Error connecting to the database: " + t);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
connect = "database connection aquired";
return connect;
}
public int getAssemblerCount() {
connect();
try {
int assemblerCount = 0;
String query = "SELECT COUNT(*) FROM assemblers";
PreparedStatement ps = con.prepareStatement(query);
ResultSet rs = ps.executeQuery();
rs.next();
assemblerCount = rs.getInt(1);
rs.close();
ps.close();
con.close();
return assemblerCount;
} catch (SQLException e) {
for (Throwable t : e)
System.err.println("Database error in getAssemblerCount " + e);
return 0;
}
}}