Rahul Gupta Rahul Gupta - 5 months ago 9
Java Question

Null values are getting inserted in database

I am checking that submitted data is not null but on simply submitting(no data) it is still inserting in the database and also i have made my columns not null but data is still getting inserted.I don't know why?

IN my Servlet

try{
String department=request.getParameter("department");
String company=request.getParameter("company");
String place=request.getParameter("place");
boolean checkd=checknull.value(department);
boolean checkc=checknull.value(company);
boolean checkp=checknull.value(place);
if(checkd==true&&checkc==true&&checkp==true) {
Connection con=ConnectionProvider.getCon();
String sql="insert into department(departmentname,company,place) values (?,?,?)";
PreparedStatement pstmt =con.prepareStatement(sql);

pstmt.setString(1,department);
pstmt.setString(2,company);
pstmt.setString(3,place);
int rs=pstmt.executeUpdate();
if(rs>0){status=true;}

if(status){
PrintWriter out= response.getWriter();
out.print("values have been inserted,"+admin);
response.sendRedirect("inserted.jsp");
}
else
{
PrintWriter out= response.getWriter();
out.print("failed to insert");
response.sendRedirect("notinsered.jsp");
}
}
else{response.sendRedirect("entry.jsp");}
}catch(SQLException e){}


This is the java class which is checking

public class checknull {
static boolean ch;
public static boolean value(String check)
{
ch = check != null;
return ch;
}

Answer

Modify your checknull class to:

public class checknull
{
    // static boolean ch; (You don't need this static variable)
    public static boolean value(String check)
    {
       return check != null && check.length() > 0;
    }
}

Also, it's a convention in Java to have class names in UpperCase.

Example:

public class CheckNull