Error:
Data source rejected establishment of connection, message from server: "Too many connections"
couldn't connect!
Apr 14, 2017 10:19:02 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [duck.reg.pack.pstcmttc] in context with path [/Duck] threw exception
java.lang.NullPointerException
I'm requesting some information through ajax from a servlet.
Code:
String UDD = null;
try {
DBConnect Database = new DBConnect();
Connection con = Database.getcon();
String query="SELECT UDD FROM userS WHERE UID=?;";
PreparedStatement ps = con.prepareStatement(query);
ps.setString(1, UID);
ResultSet rs=ps.executeQuery();
if(rs.next()){
UDD=rs.getString(1);
}
ps.close();
rs.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
Connecting:
public DBConnect(){
try{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:10021/db?useSSL=false", "root", "PASSWORD");
st = con.createStatement();
}catch(Exception ex){
System.out.println(ex.getMessage());
System.out.println("couldn't connect!");
}
}
public Connection getcon(){
DBConnect condb = new DBConnect();
Connection connect = con;
return con;
}
The request is made by user every time they click on a button which then request is performed by ajax. My servlet responds with more new info. The first time request made to this servlet works fine, but second time it outputs that exception.
The exception is thrown at line PreparedStatement ps = con.prepareStatement(query);
Based on my googling I found that This basically is due to connection leak and could either be fixed by restarting MySql server or changing it's port number. But that didn't worked for me.
The error "Too many connections" indicates that the database limit of open connections has been reached. One solution might be to configure the maximum connections allowed database-wise.
Probably more preferable would be to properly close connections after they have they been used. This can be done safely in a try...finally block like follows:
Connection con;
try {
con = Database.getcon();
} finally {
if (con != null) {
con.close();
}
}
As Connection implements AutoClosable this can be simplified via try-with-resources since Java7:
try (Connection con = Database.getcon()) {
// implementation
}
Closing the connection takes care of other JDBC resources as well as the JavaDoc states:
Releases this
Connectionobject's database and JDBC resources immediately instead of waiting for them to be automatically released.