关闭 Java 中的 MySQL 数据库连接

huangapple go评论67阅读模式
英文:

Closing MySQL Database Connections in java

问题

我的软件在使用几分钟后变得很慢,我遇到了问题。我发现问题可能是因为我有许多未关闭的连接。我有一个Java类与我的数据库连接,我从中调用连接函数到我需要执行查询的软件的各个部分。我不知道在什么时候应该关闭我的连接,因为如果我尝试在每次查询后关闭,我就无法重新执行查询,因为我会得到错误消息“在关闭数据库连接后无法执行查询”。当我把它放在我的数据库连接类中,在登录后立即关闭,我就无法执行任何查询。我应该在什么时候放置关闭数据库的函数呢?

以下是我的连接类。

public class databaseConnection {
   public static Connection connection(){
       Connection con = null;
       try{
           // 测试服务器
           //con = DriverManager.getConnection("jdbc:mysql://194.5.156.94:3306/u843360242_tukule?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC","user","password");
           // 真实服务器
           con = DriverManager.getConnection("jdbc:mysql://254gamers2.softether.net:3306/tukule_kwanza?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC","user","password");
           // 本地服务器
           //con = DriverManager.getConnection("jdbc:mysql://localhost:3306/tukule?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC","root","password");
       }catch (SQLException ex) {
            try{
               // 测试服务器
              //con = DriverManager.getConnection("jdbc:mysql://194.5.156.94:3306/u843360242_tukule?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC","user","password");
              // 真实服务器
              con = DriverManager.getConnection("jdbc:mysql://kwanzatukule.ddns.net:3306/tukule_kwanza?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC","user","password");
           }catch (SQLException x) {
                Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
       return con;
   } 
}

我需要在软件的各个部分进行以下查询。

public ArrayList categoriesQuery() {
       String query2 = "SELECT * FROM category";
        ArrayList categories = new ArrayList();
    try {
            pst = connect.prepareStatement(query2);
            rs=pst.executeQuery();
            while(rs.next()){
                Object o[]={rs.getInt("id"),
                            rs.getString("Category_Name")
                            };
                categories.add(o);         
            }
          } catch (SQLException ex) {
            Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
        }
    return categories;
    }

我应该在什么时候调用我的数据库连接函数呢?

英文:

I am having issues with my software becoming slow after some minutes of use. I figured out that the problems could be because I'm having numerous connections which i don't close. I have one java class with my Database connection from which i call the connect function to the various parts of the software that I need to execute queries. I don't know at which point I should close my connections because if I attempt to close after each query I can't have the query redone since I get the error 'Query cant be done after database connection is closed'. When I put it in my DB connection class, immediately after login, I cant execute any query. At what point should I put the db close function?
The following is my connection class.

public class databaseConnection {
   public static Connection connection(){
       Connection con = null;
       try{
           //test server
          //con = DriverManager.getConnection("jdbc:mysql://194.5.156.94:3306/u843360242_tukule?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC","user","password");
          //real server 
        con = DriverManager.getConnection("jdbc:mysql://254gamers2.softether.net:3306/tukule_kwanza?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC","user","password");
       //localhost server 
         //con = DriverManager.getConnection("jdbc:mysql://localhost:3306/tukule?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC","root","password");
       }catch (SQLException ex) {
            try{
           //test server
          //con = DriverManager.getConnection("jdbc:mysql://194.5.156.94:3306/u843360242_tukule?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC","user","password");
          //real server 
          con = DriverManager.getConnection("jdbc:mysql://kwanzatukule.ddns.net:3306/tukule_kwanza?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC","user","password");
       }catch (SQLException x) {
            Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
        }
        }
       return con;
   } 
}

I need the queries in various parts of the software as follows.

public ArrayList categoriesQuery() {
       String query2 = "SELECT * FROM category";
        ArrayList categories = new ArrayList();
    try {
            pst = connect.prepareStatement(query2);
            rs=pst.executeQuery();
            while(rs.next()){
                Object o[]={rs.getInt("id"),
                            rs.getString("Category_Name")
                            };
                categories.add(o);         
            }
          } catch (SQLException ex) {
            Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
        }
    return categories;
    }

At what point should I put my db connect function.

答案1

得分: 1

连接关闭的代码应该写在finally块中,以便在执行数据库操作时出现错误时,也能够关闭连接。您可以按以下方式编写:

public ArrayList categoriesQuery() {
    //your code
    Connection connect=null;
    try {
        connect = databaseConnection.connection();
        if(connect!=null){   
            //your code for database operations      
        }
    } catch (SQLException ex) {
        Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
    }
    finally{
        if(connect!=null){
            connect.close();
        }
    }
    return categories;
}
英文:

The code for closing connection should be written in finally block, so that if there is some error while performing database operations, then also the connection gets closed. You can do as follows :

public ArrayList categoriesQuery() {
       //your code
       Connection connect=null;
    try {
            connect = databaseConnection.connection();
            if(connect!=null){   
                //your code for database operations      
            }
          } catch (SQLException ex) {
            Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
        }
        finally{
            if(connect!=null){
                connect.close();
            }
        }
    return categories;
}

huangapple
  • 本文由 发表于 2020年5月29日 14:18:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/62079797.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定