做项目时,遇到了一个自动编号的问题。首先按照正常思路,写了一个,但是发现老是报空指针错误。
附上刚开始的代码:
public static String getFilesHtml2() {
QueryDataService queryDataService = (QueryDataService) RDPContext
.getContext().getBean("QueryDataService");
String FileShowHtml = "";
Date objDate = new Date();
SimpleDateFormat dt = new SimpleDateFormat("yyyy");
String strY = dt.format(objDate);
String strSql = "SELECT (COUNT(alh)) alh FROM wgalk";
Map<String, String> map=queryDataService.queryRowDataBySql(strSql);
String alsize=map.get("alh");
if(!alsize.equals("0")){
String strSql1="SELECT (max(alh)+1) count1 FROM wgalk where alh like '"+strY+"%'";
Map<String, String> map1=queryDataService.queryRowDataBySql(strSql1);
String count1=map1.get("count1");
if(count1.equals(null)){
FileShowHtml=strY+"0001";
return FileShowHtml;
}else{
BigDecimal bd=new BigDecimal(count1);
FileShowHtml=bd.toString();
return FileShowHtml;
}
}
FileShowHtml=strY+"0001";
return FileShowHtml;
}
发现在用map取值max时 如果查询结果为空,则无法存取在map中,后台出现空指针异常。所以改变了原来的代码,用count作为判断条件,完美运行了。
附上代码:
public static String getFilesHtml2() {
QueryDataService queryDataService = (QueryDataService) RDPContext
.getContext().getBean("QueryDataService");
String FileShowHtml = "";
Date objDate = new Date();
SimpleDateFormat dt = new SimpleDateFormat("yyyy");
String strY = dt.format(objDate);
String strSql = "SELECT (COUNT(alh)) alh FROM wgalk where alh like '"+strY+"%'";
Map<String, String> map=queryDataService.queryRowDataBySql(strSql);
String alsize=map.get("alh");
if(!alsize.equals("0")){
String strSql1="SELECT (max(alh)+1) count1 FROM wgalk where alh like '"+strY+"%'";
Map<String, String> map1=queryDataService.queryRowDataBySql(strSql1);
String count1=map1.get("count1");
BigDecimal bd=new BigDecimal(count1);
FileShowHtml=bd.toString();
return FileShowHtml;
}
FileShowHtml=strY+"0001";
return FileShowHtml;
}
总结一下。map无法存null,max()函数如果查询不到值,则会返回Null,count()函数查询不到值,会返回0;
多加练习!孰能生巧!