-1

I get java.lang.NullPointerException error while running the program. Seems like the error appears to be inside the try block: rs = st.executeQuery(query); of the method regcustomers in the below Java code. Please review my code and help me understand what I have done wrong.

import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.vastika.serlvet.dao.ConnectionDb;

public class RegistrationServlet extends HttpServlet {
    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {
        // Read the data
        String name = req.getParameter("name");
        String email = req.getParameter("email");
        String line1 = req.getParameter("addressline1");
        String city = req.getParameter("city");
        String state = req.getParameter("state");
        String country = req.getParameter("country");
        String userid = req.getParameter("username");
        String password = req.getParameter("password");
        insertToDatabase(name, email, line1, city, state, country, userid,
                password);
        // Forward to Shopping page
        req.getRequestDispatcher("shop.html").forward(req, res);
    }

    private void insertToDatabase(String name, String email, String line1,
            String city, String state, String country, String userid,
            String password) {

        ConnectionDb con = new ConnectionDb();
        Statement st = con.makeConnection();
        ResultSet rs = null;
        String query = "insert into regcustomers (Name, Email, Address, City, State, Country, Username, Password) values("+"'"+name+"'"+","+"'"+email+"'"+","+"'"+line1+"'"+","+"'"+city+"'"+","+"'"+state+"'"+","+"'"+country+"'"+","+"'"+userid+"'"+","+"'"+password+"'"+");";

        System.out.println(query);

        try {
            rs = st.executeQuery(query);
            System.out.println(rs.getRow());
            } 
        catch (SQLException e) {
            e.printStackTrace();        
            }

    }
}

and

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

public class ConnectionDb {
    public Statement makeConnection() {
        Connection conn = null;
        Statement st = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/onlineshopping", "root",
                    "test");
            st = conn.createStatement();
        } catch (Exception e) {
            e.getStackTrace();
        }
        return st;
    }
}
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
prince2369
  • 1
  • 1
  • 1
  • 3

4 Answers4

3

What's happenning is that you are getting an exception in the following code

public Statement makeConnection() {
    Connection conn = null;
    Statement st = null;
    try {
        Class.forName("com.mysql.jdbc.Driver");
        conn = DriverManager.getConnection(
                "jdbc:mysql://localhost:3306/onlineshopping", "root",
                "test");
        st = conn.createStatement();
    } catch (Exception e) {
        e.getStackTrace();
    }
    return st;
}

and then return st which is null because the code never got to conn.createStatement().

You're not actually printing the Exception by the way. Use e.printStackTrace().

Also you should actually handle the exception.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
  • I printed the Exception using e.printStackTrace(), and it is still not working. Seems like the code works fine until it goes to the point inside the try block (rs = st.executeQuery(query); which means that the makeConnection seems to be working. But not yet sure whats causing it to Null Pointer Exception. – prince2369 Sep 28 '13 at 20:37
  • My answer explains it, because of the exception your `makeConnection()` is returning `null`. What exception does it show? – Sotirios Delimanolis Sep 28 '13 at 20:38
  • This is wat the Console appeared: – prince2369 Sep 28 '13 at 20:42
  • SEVERE: Servlet.service() for servlet [RegistrationServlet] in context with path [/OnlineShopping] threw exception java.lang.NullPointerException at com.vastika.servlets.RegistrationServlet.insertToDatabase(RegistrationServlet.java:51) – prince2369 Sep 28 '13 at 20:43
  • @prince2369 That's the NPE. What does the exception caught in `makeConnection()` say? – Sotirios Delimanolis Sep 28 '13 at 20:45
  • the Excpetion does not refer to the makeConnection() method. I was not able to get exception in this method. I will post if I see it. – prince2369 Sep 28 '13 at 21:03
0

need not to put semicolon ;

String query = "insert into regcustomers (Name, Email, Address, City, State, Country, Username, Password) values("+"'"+name+"'"+","+"'"+email+"'"+","+"'"+line1+"'"+","+"'"+city+"'"+","+"'"+state+"'"+","+"'"+country+"'"+","+"'"+userid+"'"+","+"'"+password+"'"+")";

it ll return ResultSet when you ll hit SELECT query

remove that ResultSet declaration..

Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/DATABASENAME", "root", "");
Statement st = con.createStatement();

use int count = st.executeUpdate();

KhAn SaAb
  • 5,248
  • 5
  • 31
  • 52
0

You can try do this:

private void insertToDatabase(String name, String email, String line1,
            String city, String state, String country, String userid,
            String password) {

        ConnectionDb con = new ConnectionDb();
        Statement st = con.makeConnection();
        ResultSet rs = null;
        String query = "insert into regcustomers (Name, Email, Address, City, State, Country, Username, Password) values(?,?,?,?,?,?,?,?)";
        st.setString(1,name);
        st.setString(2,email);
        st.setString(3,line1);
        st.setString(4,street);
        st.setString(5,state);
        st.setString(6,country);
        st.setString(7,userid);
        st.setString(8,passwoname);

        try {
            int flag = st.executeUpdate(query);
            } 
        catch (SQLException e) {
            e.printStackTrace();        
            }

    }

I think what you wannna do is not a query, is more an update. So instead of:

rs = st.executeQuery(query);

You can do something like:

int flag = st.executeUpdate(query);

See this to have more info.

Att: u are having a NullPointer Exception because(maybe) rs = st.executeQuery(query); retrieve nothing.

Hope it helps ^^

Cold
  • 787
  • 8
  • 23
  • I can not use setString since it is undefined for Statement type. Any thoughts on this? – prince2369 Sep 28 '13 at 20:33
  • Sorry, instead of `Statment` u can use `PreparedStatement` – Cold Sep 28 '13 at 20:57
  • @Cold executeQuery(query) can never return null, hence it will not cause NullPointerException. [link](https://docs.oracle.com/javase/7/docs/api/java/sql/PreparedStatement.html#executeQuery()) ref – Arun Raaj Sep 01 '20 at 14:07
0

There is a strange situation when java.lang.NullPointerException error is triggered while executing SQL query inside try catch block. The query updates selected index in several JComboboxes. These JComboboxes are initially linked to update manually indexes according to a shema:

private void PriorityLoad6ActionPerformed(java.awt.event.ActionEvent evt) {                                              
        // TODO add your handling code here:
        NewSelectedIndex = PriorityLoad6.getSelectedIndex(); SetNewIndexes();
    } 

In this situation, when performing mysql update with a simple

PriorityLoad6.setSelectedIndex(rs.getInt("PriorityLoad_6"));

the above mentioned error is triggered. In this situation one solution is to "isolate" the code inside with an if which is not active during query. For example:

private void PriorityLoad6ActionPerformed(java.awt.event.ActionEvent evt) {                                              
                if (SaveSettings.hasFocus() == false){NewSelectedIndex = PriorityLoad6.getSelectedIndex(); SetNewIndexes();}}

This action should be of course preceded by adequately placed:

SaveSettings.requestFocus();

before calling the mysql query.

Tom Fuller
  • 5,291
  • 7
  • 33
  • 42