servlet程序中抛出的java.lang.nullpointer异常

时间:2011-03-20 05:38:41

标签: java mysql servlets myeclipse

感谢大家的精彩回答。我尝试了@Jan,@ Ratna所说的一切,但我无法克服异常。我的servlet程序中的第52行是

Statement stmt = connect.createStatement();

我在这里提供了更多代码:

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>");

您的宝贵建议将不胜感激!!

1 个答案:

答案 0 :(得分:0)

根据MySQL manual,您需要致电

Class.forName("com.mysql.jdbc.Driver").newInstance();
在尝试打开连接之前

。您正在停止forName()来电。