Sushant Baweja
Sushant Baweja

Reputation: 212

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;
}      

Upvotes: 0

Views: 399

Answers (1)

Michael Markidis
Michael Markidis

Reputation: 4191

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

EDIT: As suggested by Erwin Bolwidt, it's very likely that the database being used here is Oracle, since Oracle equates empty strings and nulls.

Therefore, this answer is only applicable to databases that treat empty strings as nulls (e.g. Oracle).

See: null-vs-empty-string-in-oracle

Upvotes: 1

Related Questions