Ashwin Satyawan :
I'm trying to access the data from a single row fetched by a select query. When I try to access the data through rs.getString()
it throws NullPointerException
.
Any method to access the data from the result set leads to a NullPointerException
. Why does this happen?
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
boolean status=true;
String email=request.getParameter("user");
String password=request.getParameter("pass");
PrintWriter pw = response.getWriter();
if (status) {
String driverName = "org.hsqldb.jdbcDriver";
String URL = "jdbc:hsqldb:hsql://localhost/";
String UID = "SA";
String PWD = "";
Connection con = null;
PreparedStatement sql = null;
ResultSet rs = null;
try {
Class.forName(driverName);
con = DriverManager.getConnection(URL, UID, PWD);
System.out.println("connected = " + con);
sql = con.prepareStatement("SELECT * FROM \"USER\" where email='"+email+"' and password='"+password+"'");
boolean sql_st=sql.execute();
System.out.println(sql_st);
rs=sql.getResultSet();
if(rs.next())
{
HttpSession hp = request.getSession(true);
rs=sql.getResultSet();
hp.setAttribute("name", rs.getString("name"));
pw.println("<html><body><h1>Welcome "+rs.getString("name")+"</h1></body></html>");
}
else
{
pw.println("<html><body><h1>invalid credentials</h1></body></html>");
pw.println("<html><body><a href=login.html>go back</a></body></html>");
}
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
else
{
pw.println("<html><body><h1>Invalid Input</h1></body></html>");
pw.println("<html><body><a href=register.html>go back</a></body></html>");
}
Swati :
You have written rs=sql.getResultSet();
two times that's the reason it return null
,Try to use PreparedStatement like below :
PreparedStatement ps= con.prepareStatement("SELECT * FROM USER where
email=? and password=?");
//putting value for placeholder (?)
ps.setString(1,email);
ps.setString(2,password);
ResultSet resultset= ps.executeQuery();
//if there is row exist then do below
if(resultset.next()){
HttpSession hp = request.getSession(true);
hp.setAttribute("name", resultset.getString("name"));
//getting name
pw.println("<html><body><h1>Welcome "+resultset.getString("name")+"</h1></body></html>");
} else {
pw.println("<html><body><h1>invalid credentials</h1></body></html>");
pw.println("<html><body><a href=login.html>go back</a></body></html>");
}