0

How to save null value as "N/A" with Java bean class? Every time it gives me exception as null. How to save the null form as "N/A"? I want to save null value as "N/A".

   package javaonline;
    import java.sql.*;
    public class SavaData {


    private String uname;

    /**
     * @return the uname
     */
    public String getUname() {
        return uname;
    }

    /**
     * @param uname the uname to set
     */
    public void setUname(String uname) {
        this.uname = uname;
    }
    public int insertdate()
    { 
    int i=0;
    try{
        Class.forName("com.mysql.jdbc.Driver");  
        Connection con=DriverManager.getConnection(  
        "jdbc:mysql://localhost:3306/test","root","root");  
      PreparedStatement st=con.prepareStatement("insert into nulltest values(?)");
      if(!uname.isEmpty() || uname!=null)
      {
          st.setString(1,uname);
      }
      else{
          st.setString(1,"N/A");      
      }
      i=st.executeUpdate();
        }
    catch(Exception e)
    {
        e.getMessage();
        System.out.print(e.getMessage());
    }
        return i;
    }

    }
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197

2 Answers2

3

You need to switch order of checks in your if to this

if(uname!=null && !uname.isEmpty())

So in this case in uname is null then uname.isEmpty() will not be called because && is a short-curciut operator.

Ivan
  • 8,508
  • 2
  • 19
  • 30
0

You can use StringUtils.defaultIfBlank() method to do this whole logic:

public int insertdate() { 
    int i=0;
    try {
        Class.forName("com.mysql.jdbc.Driver");  
        Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","root");  
        PreparedStatement st=con.prepareStatement("insert into nulltest values(?)");

        st.setString(1, StringUtils.defaultIfBlank(uname, "N/A"));
        i=st.executeUpdate();
    } catch(Exception e) {
        e.getMessage();
        System.out.print(e.getMessage());
    }
    return i;
}

Any concern, you can double check this method documentation here.

Eduardo Meneses
  • 504
  • 3
  • 18