Jump to content

[Solved] MYSQL JDBC CONNECTION ERROR


Ja23

Recommended Posts

this is  code of dbconnection.java file

 

which is inside my javaee webapplicataion 

 

my web application is hosted on heliohost 

 

 

package Database;

import java.sql.Connection;

import java.sql.DriverManager;

 

public class DbConnection {

public static Connection getconnection() {

Connection con=null;

try {

Class.forName("com.mysql.jdbc.Driver");//load the driver

                        

                        

//Create the connection

//Connection is an interface

//Drivermanager is a class and getConnetcion()is a static metod of DriverManager class whose return type is Connection

      con=DriverManager.getConnection("jdbc:mysql://localhost:3306/yo52674_wp678"+"?verifyServerCertificate=false&useSSL=false&autoReconnect=true&useUnicode=true&characterEncoding=utf8","yo52674_R","<removed>"); 

 

}

catch(Exception e){

System.out.println(e);

}

return con; //return the connection

}

}

 

my web application is trying to connect heliohost mysql database 

but it can only connect and perform queries when my heliohost phpmyadmin page is open  

after when i close php my admin it gives me error

 

e Exception Report

Message An exception occurred processing JSP page [/userregact.jsp] at line [17]

Description The server encountered an unexpected condition that prevented it from fulfilling the request.

Exception

org.apache.jasper.JasperException: An exception occurred processing JSP page [/userregact.jsp] at line [17]

14: //String feedback = request.getParameter("feedback");

15: Connection getconnection = DbConnection.getconnection();

16: //String sql=;

17: PreparedStatement st = getconnection.prepareStatement("insert into user values(?,?,?,?)");

18:

19: st.setString(1,username);

20: st.setString(2,password);

Stacktrace:

    org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:584)

    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:481)

    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:386)

    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:330)

    javax.servlet.http.HttpServlet.service(HttpServlet.java:742)

    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

Root Cause

java.lang.NullPointerException

    org.apache.jsp.userregact_jsp._jspService(userregact_jsp.java:147)

    org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)

    javax.servlet.http.HttpServlet.service(HttpServlet.java:742)

    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:443)

    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:386)

    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:330)

    javax.servlet.http.HttpServlet.service(HttpServlet.java:742)

    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

Note The full stack trace of the root cause is available in the server logs.

Apache Tomcat/8.5.24

 

this is  code of dbconnection.java file

Edited by Krydos
removed html and password
Link to comment
Share on other sites

this is  code of dbconnection.java file<br> <br>which is inside my javaee webapplicataion <br> <br>my web application is hosted on heliohost <br> <br> <br>package Database;<br>import java.sql.Connection;<br>import java.sql.DriverManager;<br> <br>public class DbConnection {<br>public static Connection getconnection() {<br>Connection con=null;<br>try {<br>Class.forName("com.mysql.jdbc.Driver");//load the driver<br>                        <br>                        <br>//Create the connection<br>//Connection is an interface<br>//Drivermanager is a class and getConnetcion()is a static metod of DriverManager class whose return type is Connection<br>      con=DriverManager.getConnection("jdbc:mysql://localhost:3306/ja190823_wp678"+"?verifyServerCertificate=false&useSSL=false&autoReconnect=true&useUnicode=true&characterEncoding=utf8","ja190823_X","<removed>"); <br> <br>}<br>catch(Exception e){<br>System.out.println(e);<br>}<br>return con; //return the connection<br>}<br>}<br> <br>my web application is trying to connect heliohost mysql database <br>but it can only connect and perform queries when my heliohost phpmyadmin page is open  <br>after when i close php my admin it gives me error<br> <br><strong>e</strong> Exception Report<br><strong>Message</strong> An exception occurred processing JSP page [/userregact.jsp] at line [17]<br><strong>Description</strong> The server encountered an unexpected condition that prevented it from fulfilling the request.<br><strong>Exception</strong><br>org.apache.jasper.JasperException: An exception occurred processing JSP page [/userregact.jsp] at line [17]<br>14: //String feedback = request.getParameter("feedback");<br>15: Connection getconnection = DbConnection.getconnection();<br>16: //String sql=;<br>17: PreparedStatement st = getconnection.prepareStatement("insert into user values(?,?,?,?)");<br>18:<br>19: st.setString(1,username);<br>20: st.setString(2,password);<br>Stacktrace:<br>    org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:584)<br>    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:481)<br>    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:386)<br>    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:330)<br>    javax.servlet.http.HttpServlet.service(HttpServlet.java:742)<br>    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)<br><strong>Root Cause</strong><br>java.lang.NullPointerException<br>    org.apache.jsp.userregact_jsp._jspService(userregact_jsp.java:147)<br>    org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)<br>    javax.servlet.http.HttpServlet.service(HttpServlet.java:742)<br>    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:443)<br>    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:386)<br>    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:330)<br>    javax.servlet.http.HttpServlet.service(HttpServlet.java:742)<br>    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)<br><strong>Note</strong> The full stack trace of the root cause is available in the server logs.<br>Apache Tomcat/8.5.24<br> <br>this is  code of dbconnection.java file

And my user name is ja190823

Link to comment
Share on other sites

In your DbConnection class, if there is an exception constructing the connection, you are catching it and using System.out.println, then returning the null connection.  Printing it that way won't show you the error message in the browser, it goes to the stdout of the JVM running Tomcat.

 

It might help you to understand what is going wrong if you can see that exception during the JDBC connection attempt.  You could try debugging by just not catching or rethrowing it.  Or look in the tomcat log files, usually System.out is set up to redirect to one of them.

 

The exception you have shown is coming from the null returned by your static method, but it can't show information about why it was null.

 

Also, the formatting of your post makes it very hard to read.

  • Like 1
Link to comment
Share on other sites

Dbconnection.java

 

package Database;

import java.sql.Connection;

import java.sql.DriverManager;

 

public class DbConnection {

public static Connection getconnection()throws Exception {

Connection con=null;

try {

Class.forName("com.mysql.jdbc.Driver");//load the driver

 

 

//Create the connection

//Connection is an interface

//Drivermanager is a class and getConnetcion()is a static metod of DriverManager class whose return type is Connection

 

con=DriverManager.getConnection("jdbc:mysql://localhost:3306/ja190823_wp640"+"?verifyServerCertificate=false&useSSL=false&autoReconnect=true&useUnicode=true&characterEncoding=utf8","ja190823_R","password ");

// con=DriverManager.getConnection("jdbc:mysql://localhost/ja190823_wp640","ja190823_R","password");

//type iv url=jdbc:oracle:thin:@//localhost:1521/xe

//user name=infinite

//password=5151

}

catch(Exception e){

System.out.println(e);

}

return con; //return the connection

}

}

 

 

userregact.jsp

 

 

<%@page import="java.sql.PreparedStatement"%>

<%@page import="Database.DbConnection"%>

<%@page import="java.sql.ResultSet"%>

<%@page import="java.sql.Statement"%>

<%@page import="java.sql.Connection"%>

<%@page import="java.util.*,java.text.SimpleDateFormat,java.util.Date,java.io.FileInputStream,java.io.FileOutputStream,java.io.PrintStream"%>

 

<% try{

String username= request.getParameter("username");

String password = request.getParameter("password");

String email= request.getParameter("email");

String mobile = request.getParameter("mobile");

//String brand = request.getParameter("brand");

//String feedback = request.getParameter("feedback");

Connection getconnection = DbConnection.getconnection();

//String sql=;

PreparedStatement st = getconnection.prepareStatement("insert into user values(?,?,?,?)");

 

st.setString(1,username);

st.setString(2,password);

st.setString(3,mobile);

st.setString(4, email);

int i=st.executeUpdate();

if(i>0){

response.sendRedirect("user.jsp?msg=success");

 

} }

catch(Exception e)

{out.println( " </br></br></br>THIS IS EXCEPTION"+e+"</br></br></br>" );}

%>

 

 

Error/Exception which is occurring after closing phpmyadmin

 

 

THIS IS EXCEPTIONjava.lang.NullPointerException

Link to comment
Share on other sites

This is what I think is going on and how I suggest you debug it:

 

The NullPointerException you see is because your [DbConnection.getconnection()] call is returning null.  You see that message in your browser because [out] in the JSP page is set up to "write there".

 

In your [DbConnection.getconnection()] method, you set the connection to null.  Then in your try block, an exception happens, you catch and print that exception, and return the null.  You don't see the exception because you use [system.out.println] and that write to the stdout of the JVM Catalina is using.  Usually Tomcat setups redirect that to a log file.

 

There are 2 things in your [try] block that are likely to fail with an exception.  The first is a problem coming from the classloader when you use it to load the driver.  The second is when you connect to the database.

 

To understand what is going wrong, seeing what exception you received would be helpful.  To see that, you have to look in the catalina logs to see if the exception message you printed to stdout was redirected to there.  Or, better, change your method to NOT swallow and print the exception to stdout.  For your debugging, either don't catch the exception, or if you do want to print it, rethrow it after.  Then the root cause exception, and not just a null, will be trapped and handled in the try/catch block in your JSP page, and you can see it on the browser.

  • Like 1
Link to comment
Share on other sites

Thank You very much krydos sir and loratadi sir

 

THIS IS

 

DBConnection.java

 

package Database;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

 

import java.sql.Connection;

import java.sql.DriverManager;

 

public class DbConnection {

public static Connection getconnection()throws Exception {

Connection con=null;

try {

Class.forName("com.mysql.jdbc.Driver");//load the driver

 

 

//Create the connection

//Connection is an interface

//Drivermanager is a class and getConnetcion()is a static metod of DriverManager class whose return type is Connection

 

con=DriverManager.getConnection("jdbc:mysql://localhost:3306/ja190823_wp640"+"?verifyServerCertificate=false&useSSL=false&autoReconnect=true&useUnicode=true&characterEncoding=utf8","ja190823_R","<remove>");

// con=DriverManager.getConnection("jdbc:mysql://localhost/ja190823_wp640","ja190823_R","remove ");

//type iv url=jdbc:oracle:thin:@//localhost:1521/xe

//user name=infinite

//password=5151

}

catch(Exception e){

System.out.println(e);

}

return con; //return the connection

}

 

 

public static Connection getconnection(HttpServletResponse res )throws Exception {

Connection con=null;

 

try {

Class.forName("com.mysql.jdbc.Driver");//load the driver

 

 

//Create the connection

//Connection is an interface

//Drivermanager is a class and getConnetcion()is a static metod of DriverManager class whose return type is Connection

 

con=DriverManager.getConnection("jdbc:mysql://localhost:3306/ja190823_wp640"+"?verifyServerCertificate=false&useSSL=false&autoReconnect=true&useUnicode=true&characterEncoding=utf8","ja190823_R","<remove>");

// con=DriverManager.getConnection("jdbc:mysql://localhost/ja190823_wp640","ja190823_R","jay@1234");

//type iv url=jdbc:oracle:thin:@//localhost:1521/xe

//user name=infinite

//password=5151

}

catch(Exception e){

PrintWriter out=res.getWriter();

out.println("INSIDE GET FUNCTION"+e);

}

return con; //return the connection

}

 

}

 

 

 

userregact.jsp

<%@page import="java.sql.PreparedStatement"%>

<%@page import="Database.DbConnection"%>

<%@page import="java.sql.ResultSet"%>

<%@page import="java.sql.Statement"%>

<%@page import="java.sql.Connection"%>

<%@page import="java.util.*,java.text.SimpleDateFormat,java.util.Date,java.io.FileInputStream,java.io.FileOutputStream,java.io.PrintStream"%>

 

<% try{

String username= request.getParameter("username");

String password = request.getParameter("password");

String email= request.getParameter("email");

String mobile = request.getParameter("mobile");

//String brand = request.getParameter("brand");

//String feedback = request.getParameter("feedback");

Connection getconnection = DbConnection.getconnection(response);

//String sql=;

PreparedStatement st = getconnection.prepareStatement("insert into user values(?,?,?,?)");

 

st.setString(1,username);

st.setString(2,password);

st.setString(3,mobile);

st.setString(4, email);

int i=st.executeUpdate();

if(i>0){

response.sendRedirect("user.jsp?msg=success");

 

} }

catch(Exception e)

{out.println( " </br></br></br>THIS IS EXCEPTION"+e+"</br></br></br>" );}

%>

 

 

 

 

 

 

 

 

 

 

 

 

 

INSIDE GET FUNCTIONcom.mysql.jdbc.exceptions.MySQLNonTransientConnectionException: Server connection failure during transaction. Due to underlying exception: 'com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: User ja190823_R already has more than 'max_user_connections' active connections'. ** BEGIN NESTED EXCEPTION ** com.mysql.jdbc.exceptions.MySQLSyntaxErrorException MESSAGE: User ja190823_R already has more than 'max_user_connections' active connections STACKTRACE: com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: User ja190823_R already has more than 'max_user_connections' active connections at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:936) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2870) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:812) at com.mysql.jdbc.MysqlIO.secureAuth411(MysqlIO.java:3269) at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1182) at com.mysql.jdbc.Connection.createNewIO(Connection.java:2772) at com.mysql.jdbc.Connection.(Connection.java:1531) at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:266) at java.sql.DriverManager.getConnection(DriverManager.java:664) at java.sql.DriverManager.getConnection(DriverManager.java:247) at Database.DbConnection.getconnection(DbConnection.java:45) at org.apache.jsp.userregact_jsp._jspService(userregact_jsp.java:145) at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70) at javax.servlet.http.HttpServlet.service(HttpServlet.java:742) at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:443) at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:386) at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:330) at javax.servlet.http.HttpServlet.service(HttpServlet.java:742) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:504) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81) at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:650) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803) at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:790) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1459) at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Thread.java:748) ** END NESTED EXCEPTION ** Attempted reconnect 3 times. Giving up.

 

 

THIS IS EXCEPTIONjava.lang.NullPointerException

Link to comment
Share on other sites

Good work, now we can see the root cause exception and read its message, which is [User ja190823_R already has more than 'max_user_connections' active connections]

 

So it failed because your user is making too many connections to the database.

 

I think this is because you are making a new connection for each one of your JSP requests.  Try to call [close] on the Connection when you are done with it.

 

Also, typically the management of connections, creation, pooling and reuse of them and so on is handled for you by the application container or servlet you are using.  For example, with Tomcat, you can set up a database in the context using context.xml or server.xml and then in your program get the connection using InitialContext.  This gets better performance than always creating/closing connections.

 

If you are interested in learning about this, here are some documentations.

 

Here is a document on how to set up the resource:

https://dev.mysql.com/doc/connector-j/8.0/en/connector-j-usagenotes-tomcat.html

 

And this document has an example of how you can get that connection by use of DataSource and InitialContext

https://dev.mysql.com/doc/connector-j/8.0/en/connector-j-usagenotes-j2ee-concepts-connection-pooling.html#connector-j-examples-connectionpool-j2ee

  • Like 1
Link to comment
Share on other sites

last problem was solved i have used st.closed() method
and con.close() method thankyou very much   ^_^
loratadi

:)

 
a.jsp code is returning null value while trying to fetch session values      
 
session id of a.jsp and 
userregact.jsp is different like every time it creates new session 
 
in  my web.xml i have specified time for session timeout
 
web.xml
 <session-config>
      <session-timeout>3</session-timeout>
  </session-config>

 

 
 
 
 
userregact.jsp
if(rs.next())
{
                        request.setAttribute("s",session.getId());
                         email = rs.getString("email");   
                       session.setAttribute("username",username);
                       session.setAttribute("email",email);
                      
                       response.sendRedirect("a.jsp?p="+session.getId());
//response.sendRedirect("userhome.jsp?msg=success");
 
 
}

 

 

 

a.jsp
 
<html>
    <head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <p><%
            try{%>
Id OF SESSION <%= session.getId()%>
       
username <%= (String)session.getAttribute("username")%>
 
       
email <%= (String)session.getAttribute("email")%>
     sessionold s <%= (String)session.getAttribute("s")%>
req p attribute session id <%=(String) request.getAttribute("p")%>
      
password<%=(String) session.getAttribute("password")%>
<%}
catch(Exception e)
{
out.println("my error is e"+e);
 
}
%>        </p>
        <h1>Hello World!</h1>
    </body>
</html> 
Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...