java中的静态变量问题

Dee*_*pak 3 java mysql connection static

我在我的应用程序中使用静态变量.现在应用程序状态完成后,我在垃圾回收中遇到了问题.声明为static的变量永远不会被垃圾收集,我的内存很快耗尽.

具体问题是关于mysql连接.我将连接变量存储在静态变量中,因此每次运行查询时都不必打开连接.这导致每次使用连接变量执行查询时都使用所有内存的问题,并且未释放使用的内存.将连接变量存储在静态变量中是一个好主意吗?当我每次尝试打开和关闭连接而没有静态变量时,我解决了内存管​​理问题,但应用程序的响应速度减慢了10到20倍.

您是否需要更多信息才能理解这个问题?如果是,请在没有投票的情况下问我.谢谢!

编辑 这是我的连接器类

import java.sql.*;

public class connect {

    public Connection conn = null;

    public connect() {
        try {
            if (conn == null) {
                String userName = "root";
                String password = "password";               
                String url = "jdbc:mysql://localhost/pos?zeroDateTimeBehavior=convertToNull";                
                Class.forName("com.mysql.jdbc.Driver").newInstance();
                conn = DriverManager.getConnection(url, userName, password);               
                System.out.println("Database connection established");               
            }
        } catch (Exception e) {
            System.err.println("Cannot connect to database server");           
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我存储连接的类

public class variables {
    public static connect con = new connect();
}
Run Code Online (Sandbox Code Playgroud)

而这个方法我用来执行查询

public class mysql_query {
public static ResultSet execute_mysql(Connection con, String sqlStatement) {
        try {
            //ResultSet result = null;
            java.sql.Statement cs = con.createStatement();
            ResultSet result = cs.executeQuery(sqlStatement);
            return result;
        } catch (SQLException ex) {
            Logger.getLogger(mysql_query.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }

    }

 public static void main(String args[]){
     String sql = "SELECT * FROM pos_user_login WHERE moderator='1' AND "
                    + "company_id='1'";

     ResultSet rs = execute_mysql(variables.con.conn, sql);
  }
}
Run Code Online (Sandbox Code Playgroud)

Mic*_*les 5

也许最好是使用连接池而不是静态变量...连接池维护一堆打开的连接,并在需要时将它们提供出去.应该解决你的性能问题和你的记忆问题.


Luk*_*der 5

只是一个想法:你可能没有正确关闭你的ResultSetStatement对象.如果不这样做,MySQL JDBC驱动程序可能会保留许多您不再需要的资源.特别是ResultSet可能非常痛苦,因为数据库游标的某些部分仍然在内存中.

给你一个想法的一个例子是:

PreparedStatement stmt = null;
ResultSet rs = null;

try {
    stmt = connection.prepareStatement(...);
    rs = stmt.executeQuery();
}

// Close your resources in a finally block! Because the finally block
// is executed even if you have exceptions in the try block.
// If you do this a lot of times, write utility methods...
finally {
    try {
        if (rs != null) {
            rs.close();
        }
    } catch (SQLException ignore) {}

    try {
        if (stmt != null) {
            stmt.close();
        }
    } catch (SQLException ignore) {}
}
Run Code Online (Sandbox Code Playgroud)