views:

181

answers:

7

I my web app, i have search fiedl where i get some string and a combo box. So, i am sending two arguments to the remote function.

I want to check the user input is not null and not empty. So, then i can construct a valid query.

public ArrayList findEmployees(String str, int dep)throws ClassNotFoundException, SQLException{
    System.out.println("List IN");
    ArrayList list = new ArrayList();
    java.sql.Statement stmt;
    java.sql.ResultSet rs;
    Class.forName("com.mysql.jdbc.Driver");
    String url = "jdbc:mysql://localhost:3306/general";
    java.sql.Connection con = DriverManager.getConnection(url, "root", "1234");
    System.out.println("URL: " + url);
    System.out.println("Connection: " + con);
    stmt = con.createStatement();
    stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
            ResultSet.CONCUR_READ_ONLY);
    String qry = "SELECT * FROM PERSON ";
    String werstr = "WHERE";
    if(str!= null && str != "**here i want to check the 'str' is empty or not." )
    {
        qry += werstr + " NAME LIKE '%"+str+"%'";
        System.out.println(qry);
        werstr = "AND";
    }
    if(dep != 0)
    {
        qry += werstr + "dept="+dep;
    }
    qry += ";";
    System.out.println(qry);
    rs = stmt.executeQuery(qry);
    while (rs.next()) {
        Employee employee = new Employee();
        String name = rs.getString(2);
        employee.setName(name);
        int id = rs.getInt(1);
        employee.setId(id);
        int dept = rs.getInt(4);
        employee.setDept(dept);
        int age = rs.getInt(3);
        employee.setAge(age);
        list.add(employee);
    }
    System.out.println("List Out");
    return list;
}

Any suggestons

+3  A: 
str != null && str.length() != 0

alternatively

str != null && !str.equals("")

or

str != null && !"".equals(str)

Note: The second check (first and second alternatives) assumes str is not null. It's ok only because the first check is doing that (and Java doesn't does the second check if the first is false)!

IMPORTANT: DON'T use == for string equality. == checks the pointer is equal, not the value. Two strings can be in different memory addresses (two instances) but have the same value!

helios
+3  A: 

How about:

if(str!= null && str.length() != 0 )
codaddict
+8  A: 

What about isEmpty() ?

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

Beware, it's only available since Java SE 1.6. You have to check str.length() == 0 on previous versions.

Colin Hebert
Since Java 1.6... nice. I didn't knew it.
helios
+8  A: 

I like to use Apache commons-lang for these kind of things, and especially StringUtils utility class:

if (StringUtils.isNotBlank(str)) {
    ...
} 
romaintaz
isn't Apache commons-lang an overkill if you can just use isEmpty? Just curious.
zengr
@zengr - no, because you most certainly would use other things as well :)
Bozho
@zengr Indeed, if you only use `isEmpty` or `isBlank`, maybe it is not usefull to include a third-party library. You can simply create your own utility class to provide such method. However, as Bozho explain, the `commons-lang` project provide many usefull methods!
romaintaz
+1  A: 

Almost every library I know defines a utility class called StringUtils, StringUtil or StringHelper, and they usually include the method you are looking for.

My personal favorite is Apache Commons / Lang, where in the StringUtils class, you get both the

  1. StringUtils.isEmpty(String) and the
  2. StringUtils.isBlank(String) method

(The first checks whether a string is null or empty, the second checks whether it is null, empty or whitespace only)

There are similar utility classes in Spring, Wicket and lots of other libs. If you don't use external libraries, you might want to introduce a StringUtils class in your own project.

seanizer
+1  A: 

As seanizer said above, Apache StringUtils is fantastic for this, if you were to include guava you should do the following;

public List<Employee> findEmployees(String str, int dep) {
 Preconditions.checkState(StringUtils.isNotBlank(str), "Invalid input, input is blank or null");
 /** code here **/
}

May I also recommend that you refer to the columns in your result set by name rather than by index, this will make your code much easier to maintain.

BjornS
No need to use apache commons from guava though, there is a Strings class in guava too: http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/base/Strings.html
seanizer
True, I simply prefer the Apache StringUtil class over the Guava one, I find it more readable.
BjornS
+1  A: 

I got bored, have a free refactoring. Its a little cleaner but not pristine.

public class ALittleCleaner {

public List<Employee> findEmployees(String str, int dep) throws ClassNotFoundException, SQLException {
    log("List IN");
    List<Employee> list = Lists.newArrayList();

    Connection con = getConnection();
    Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
    String qry = buildQueryString(str, dep);
    log(qry);
    ResultSet rs = stmt.executeQuery(qry);
    parseResults(list, rs);
    log("List Out");
    return list;
}

private void parseResults(List<Employee> list, ResultSet rs) throws SQLException {
    while (rs.next()) {
        Employee employee = new Employee();
        String name = rs.getString(2);
        employee.setName(name);
        int id = rs.getInt(1);
        employee.setId(id);
        int dept = rs.getInt(4);
        employee.setDept(dept);
        int age = rs.getInt(3);
        employee.setAge(age);
        list.add(employee);
    }
}

private String buildQueryString(String str, int dep) {
    String qry = "SELECT * FROM PERSON ";
    StringBuilder sb = new StringBuilder();

    if (StringUtils.isNotBlank(str)) {

        sb.append("WHERE NAME LIKE '%").append(str).append("%'");
        log(qry);
    }
    if (dep != 0) {

        if (sb.toString().length() > 0) {
            sb.append(" AND ");
        } else {
            sb.append("WHERE ");
        }
        sb.append("dept=").append(dep);
    }

    qry += sb.append(";").toString();
    return qry;
}

private Connection getConnection() throws SQLException, ClassNotFoundException {
    Class.forName("com.mysql.jdbc.Driver");

    String url = "jdbc:mysql://localhost:3306/general";

    java.sql.Connection con = DriverManager.getConnection(url, "root", "1234");

    log("URL: " + url);
    log("Connection: " + con);
    return con;
}

private void log(String out) {
    // Replace me with a real logger

    System.out.println(out);

}

class Employee implements Serializable {
    private static final long serialVersionUID = -8857510821322850260L;
    String name;
    int id, dept, age;

    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getId() {
        return this.id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getDept() {
        return this.dept;
    }

    public void setDept(int dept) {
        this.dept = dept;
    }

    public int getAge() {
        return this.age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

}
BjornS