我在GWT中执行查询数据库的RPC,我的程序中有内存泄漏,我对我设置类的方式有很强的怀疑。目前,我必须在我拥有的每个方法中连接到数据库,然后在方法结束时关闭该连接。这样做会导致内存泄漏吗?我觉得编程这样会导致更多代码并且效率非常低但我找不到很多好的样本,有人可以提出更好的方法吗?名称,IP已被更改,我发布了连接方法以及其他方法的编写示例。
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;
}
}}
答案 0 :(得分:1)