开发者

Returning a null array string in java

I am having a java class where I am executing a query and assigning the query result to an string array, finally return the array.

Everything works fine. But I want to return "开发者_Python百科no data" if the db values are empty (not the whole array). what can I do for this?

Code:

query="select `t1`,`t2`,`t3` from test";

                PreparedStatement pre = conn.prepareStatement(query);
                ResultSet res = pre.executeQuery();
                String val[][] = new String[res.getRow()][3];
           while (res.next()) {
                val[i][0] = res.getString(1);
                val[i][1] = res.getString(2);
                val[i][2] = res.getString(3);
                i++;
              }

                res.close();
                conn.close();
                pre.close();

                return (val);

(Where I want the val[1][1] to be "No Data" if res.getString(2) is null).


No Data seems to be a value you display more than a logical value.

So you should decide of a special value and display it in a special way. We usually call this a sentry value.

This value could be null or a string that can't be in your db. (maybe it doesn't apply here as everything is often possible in a db).

Also note that it could be attractive to use an exception instead of this special value but it is actually a very poor use of exceptions, mostly for performance issues and hence it is a design to avoid if possible except if this value can lead to problems for your clients classes.


try this way

val[i][0] = (res.getString(1)!=null & !res.getString(1).equals(""))?res.getString(1).equals(""):"No Data";

val[i][1] = (res.getString(1)!=null & !res.getString(2).equals(""))?res.getString(3).equals(""):"No Data";

val[i][2] = (res.getString(1)!=null & !res.getString(3).equals(""))?res.getString(3).equals(""):"No Data";

use the only one "&" what happen when you check the condition with && first it will check for the first i.e. rs.getString(1)!=null if this is null or not it will check for the another condition i.e. rs.getString(1).equal("") so if you check and it will null then in second condition it will cause the error for NullPointerException.

while if you use only one & then it will check first condition if that was true then only it go for check the another condition otherwise not.


Add small helper methods like this:

public static String getValue(String value) {
  return getValue(value, "No Data");
}

public static String getValue(String value, String default) {
  return value == null ? default : value;
}

Use it like this:

val[i][0] = getValue(res.getString(1));  // standard 
val[i][0] = getValue(res.getString(1), "NULL");  // with custom default message
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜