Search code examples
javamysqlservletsmyeclipse

java.lang.nullpointer exception thrown in servlet program


Thanks for those wonderful answers everyone.I tried everything said by @Jan, @Ratna yet I am not able to overcome the exception. Line No.52 in my servlet program is

Statement stmt=connect.createStatement();

I present more of the code here:

public class s3 extends HttpServlet
{
String message,seat_no,name,ans1,ans2,ans3,ans4,ans5;
int Total=0;
Connection connect;
Statement stmt=null;
ResultSet rs=null;
public void doPost(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException
{
try
{
String url="jdbc:mysql://localhost:3306/test";
Class.forName("com.mysql.jdbc.Driver");
connect=DriverManager.getConnection(url,"root","root");
message="Connection Sucessfull";
}
catch(ClassNotFoundException cnfex){
cnfex.printStackTrace();
}
catch(SQLException sqlex){
sqlex.printStackTrace();
}
catch(Exception excp){
excp.printStackTrace();
}
seat_no=request.getParameter("seat_no");
name=request.getParameter("name");
ans1=request.getParameter("group1");
ans2=request.getParameter("group2");
ans3=request.getParameter("group3");
ans4=request.getParameter("group4");
ans5=request.getParameter("group5");
if(Boolean.getBoolean(ans1) == true)
    Total+=2;
if(Boolean.getBoolean(ans2) == false)
    Total+=2;
if(Boolean.getBoolean(ans3) == true)
    Total+=2;
if(Boolean.getBoolean(ans4) == false)
    Total+=2;
if(Boolean.getBoolean(ans5) == false)
    Total+=2;
try
{
   if(Total>0)// Just a condition.. !
   {
    Statement stmt=connect.createStatement();
    String query="INSERT INTO st1("+"seat_no,name,marks"+")VALUES('"+seat_no+"','"+name+"','"+Total+"')";
    stmt.executeUpdate(query);
    stmt.close();
  }
}
catch(SQLException ex){
}
response.setContentType("text/html");
PrintWriter out=response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("</head>");
out.println("<body bgcolor=pink>");
out.println("<h1>"+message+"</h1>\n");
out.println("<h3>database updated");
out.println("<br>");
out.println("<b>"+"datbase is follows");
out.println("<table border=5>");
try
{
Statement stmt=connect.createStatement();
String query="SELECT * FROM st1";
rs=stmt.executeQuery(query);
out.println("<th>"+"seat_no"+"</th>");
out.println("<th>"+"name"+"</th>");
out.println("<th>"+"marks"+"</th>");

Your valuable suggestions will be appreciated !!


Solution

  • According to the MySQL manual, you need to call

    Class.forName("com.mysql.jdbc.Driver").newInstance();
    

    before trying to open a connection. You're stopping with the forName() call.