简体   繁体   English

JDBC错误“连接过多”

[英]JDBC error “Too many connections”

I have created a java swing application in which basically user logs in gets to the main window and select a jmenu item which leads the user to a new window where you can input data to the database. 我创建了一个Java swing应用程序,基本上用户在其中登录都会进入主窗口,然后选择一个jmenu项,它将用户引导至一个新窗口,您可以在其中向数据库输入数据。

In this 3rd window where the data base is updated, i have used a jcombobox where the items in it are loaded from the database. 在更新数据库的第三个窗口中,我使用了一个jcombobox,其中的项目是从数据库中加载的。

when i debug it, it runs properly. 当我调试它时,它可以正常运行。 But when I try to run the application top to bottom, the updating window is displayed but the jcombobox items are not being loaded. 但是,当我尝试从上到下运行该应用程序时,会显示更新窗口,但jcombobox项未加载。 it gives an error saying too many connections. 它给出一个错误,说明连接过多。

as far as my knowledge, ive closed all the connections properly. 就我所知,我已经正确关闭了所有连接。

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
String un=jTextField1.getText();
String pwd=jPasswordField1.getText();
   if(un.isEmpty()){
       JOptionPane.showMessageDialog(this,"User Name is empty");
   }
   else  if(pwd.isEmpty()){
       JOptionPane.showMessageDialog(this,"Password is empty");
   }
   else{
    try {
         DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss");
        Calendar cal = Calendar.getInstance();

        ResultSet rs=new DBconnect().getdata("SELECT * FROM user");
        rs.next();
        if ((rs.getString("Name").equals(un))&&(rs.getString("pw").equals(pwd))){
            new DBconnect().putdata("INSERT INTO login (Date,User) VALUES('"+dateFormat.format(cal.getTime())+"','"+un+"')");
          new  MainWindow().setVisible(true);

          this.dispose();
        }
        else{
            JOptionPane.showMessageDialog(this, "Invalid user name or password");
            jTextField1.setText("");
            jPasswordField1.setText("");
        }
        rs.close();
    } catch (Exception ex) {
        Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
    }

   }
}                                        

above is my login forms code. 上面是我的登录表单代码。

 public MainWindow() {
    setExtendedState(JFrame.MAXIMIZED_BOTH);
    new Thread(){
        public void run(){
            while(true){
       DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
       Calendar cal = Calendar.getInstance();

       DateFormat dateFormat2 = new SimpleDateFormat("yyyy/MM/dd");
       Calendar cal2 = Calendar.getInstance();

       jLabel1.setText(dateFormat.format(cal.getTime()));

                try {
                    ResultSet rs=new DBconnect().getdata("SELECT COUNT(Pno) FROM medicalhistory WHERE Date ='"+dateFormat2.format(cal2.getTime())+"'");
                    rs.next();
                    jLabel4.setText(rs.getString("COUNT(Pno)").toString());


                    ResultSet rs2=new DBconnect().getdata("SELECT SUM(Amount) FROM income WHERE Date ='"+dateFormat2.format(cal2.getTime())+"'");
                    rs2.next();
                    jLabel5.setText(rs2.getString("SUM(Amount)").toString());
                    rs2.close();
                    rs.close();

                } catch (Exception ex) {
                    Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }.start();


    initComponents();
}

above is the main windows' code where ive used connections. 上面是我使用连接的主要窗口代码。 these work properly. 这些工作正常。

public addnewpatient() {
            setExtendedState(JFrame.MAXIMIZED_BOTH);


    initComponents();
        try {
                try (ResultSet rs3 = new DBconnect().getdata("SELECT Name FROM drugstock WHERE stockAmount >0")) {
                    Vector v= new Vector();
                    while(rs3.next()){
                        String ids = rs3.getString("Name");
                        v.add(ids);
                        jComboBox1.addItem(ids);
                    }
                    jComboBox1.addItem("Null");
                  rs3.close();
                }

    }


        catch (Exception ex) {
        Logger.getLogger(addnewpatient.class.getName()).log(Level.SEVERE, null, ex);
    }
}

above code gives the too many connections error. 上面的代码给出了太多的连接错误。

putdata and getdata are two methods ive created in the connection class for easiness. 为方便起见,putdata和getdata是在连接类中创建的两个方法。

:) Thanx in advance :) :)预先感谢:)

I can see you are creating connections in below line : 我可以看到您在下面的行中创建连接:

ResultSet rs3 = new DBconnect().*;

Then you are just closing ResultSet - rs3.close(); 然后,您只是关闭ResultSet-rs3.close();。

Who takes care of closing your database connections and how? 谁负责关闭数据库连接以及如何关闭?

How to fix now: 现在如何解决:

There is no need of internal try block in you code - so remove it. 您的代码中不需要内部try块-因此将其删除。

Getting connection : 建立连接:

DBconnect dbconnect = new DBconnect();
ResultSet rs3 = dbconnect..getdata("...");;

Before exiting try block - close ResultSet, Connection. 退出try块之前-关闭ResultSet,连接。

rs3.close();
dbconnect.close();

Replace your DBConnect.java as below: 替换您的DBConnect.java,如下所示:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Date;

public class DBconnect {
    static String url = "jdbc:mysql://localhost:3306/ppmgt";
    Connection conn;
    Statement st;

    public DBconnect() {

        try {
            Class.forName("com.mysql.jdbc.Driver");
            this.conn = DriverManager.getConnection(url, "root", "");
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public void putdata(String sql) throws Exception {
        st = this.conn.createStatement();
        st.executeUpdate(sql);
    }

    public ResultSet getdata(String sql) throws Exception {
        Statement st = this.conn.createStatement();
        return st.executeQuery(sql);
    }

    public void close() {
        try {
            this.conn.close();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static long compareTo(Date date1, Date date2) {
        return date1.getTime() - date2.getTime();
    }
}

There are no other changes needed in classes using DBconnect class other than closing connection: 除了关闭连接之外,使用DBconnect类的类没有其他需要的更改:

dbconnect.close();
public class DBconnect {
static String url = "jdbc:mysql://localhost:3306/ppmgt";



public static Connection con() throws Exception {
    Class.forName("com.mysql.jdbc.Driver");
    Connection c = DriverManager.getConnection(url, "root", "");
    return c;
}

public void putdata(String sql) throws Exception {
    Connection c = DBconnect.con();
    Statement st = c.createStatement();
    st.executeUpdate(sql);

}

public ResultSet getdata(String sql) throws Exception {
    Connection c = DBconnect.con();
    Statement st = c.createStatement();
    ResultSet r = st.executeQuery(sql);

    return r;
}

    public static long compareTo(Date date1,Date date2) {
    return date1.getTime() - date2.getTime();
}

} }

this is my DBconnect class 这是我的DBconnect类

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM