private String getSQL(){
String SQL="select t.id from test where 1=1";
if (userId != null && !userId.equals("")){
SQL+=" and userId='"+userId+"' ";
}
return SQL;
}
PreparedStatement ps = con.prepareStatement(SQL);
String SQL="select t.id from test where 1=1";
if (userId != null && !userId.equals("")){
SQL+=" and userId='"+userId+"' ";
}
return SQL;
}
PreparedStatement ps = con.prepareStatement(SQL);
解决方案 »
- 显示bookid抛出空指针异常
- 关于网站的个人头像上传问题 jsp的网站
- eclipse 打不开 在线等!!
- 菜鸟求助: JSP程序编写语法问题, 这句代码到底是Java代码还是Html代码.
- 100 分求分 为会么在JBuilder的工程里的JAVA文件 引入包时不能用*
- sturus的标签文档chm的,谁有,就是Struts Taglibs-chm.chm,给我发一份,或者给我网址,谢谢
- jms入门问题
- 简单的概念问题--订单的异步处理的消息驱动BEAN--这句话是什么意思??请大虾指教!!
- 一个关于用EJB作工作流的问题
- Spring 注解方式注入service
- hibernate问题,求解
- 那个大虾用过lucene?进来小弟有些问题咨询
String SQL="select t.id from test where 1=1";
if (userId != null && !userId.equals("")){
SQL+=" and userId='"+userId+"' ";
}
return SQL;
}
PreparedStatement ps = con.prepareStatement(SQL);
userId ,opId,dpt这三个字段如果为空则不加条件。用组合语句的方式是可以实现的。而用prepareStatement可以不可以实现我还不知道,
prepareStatement这样写:
sql.append("select t.id from test where 1=1");
sql.append(" and userId = ? ");
sql.append(" and opId = ? ");
sql.append(" and dptId = ? ");stmt = conn.prepareStatement(sql.toString());
stmt.setInt(1, check1);
stmt.setInt(2, check2);
stmt.setString(3, group_code);rs = stmt.executeQuery();
这里的问题就在set的时候一共会有几个参数和哪几个参数不得而知。
if(!"".equals(check1)){
sql.append(" and userId = ? ");
}
if(!"".equals(check2)){
sql.append(" and opId = ? ");
}
...stmt = conn.prepareStatement(sql.toString());
int i=0;
if(!"".equals(check1)){
stmt.setInt(i++, check1);
}
...
rs = stmt.executeQuery();
明白?
if (userId != null && !userId.equals("")){
sql.append(" and userId = ? ");
}
if (opId != null && !opId.equals("")){
sql.append(" and opId = ? ");
}
if (dptId != null && !dptId.equals("")){
sql.append(" and dptId = ? ");
}
int i=1;
if (userId != null && !userId.equals("")){
stmt.setInt(i++, userId);
}
if (opId != null && !opId.equals("")){
stmt.setInt(i++, opId);
}
if (dptId != null && !dptId.equals("")){
stmt.setInt(i++, dptId);
}
int i=0;
if(!"".equals(check1)){
stmt.setInt(i++, check1);//错了,parameterIndex从1开始
}
PreparedStatement stmt = null;
ResultSet rs = null;
String projectId = "";
StringBuffer sql = new StringBuffer("");
sql.append("select t.id from test where 1=1 and (t.opId =? or -1=?)");
sql.append(" and (t.dptId=? or -1=?)");
try {
conn = ConnTool.getConnection();
stmt = conn.prepareStatement(sql.toString());
if (!projectName.equals("")) {
stmt.setString(1,projectName);
stmt.setString(2,projectName);
}else{
stmt.setInt(1,-1);
stmt.setInt(2,-1);
}
if (!dpt.equals("")) {
stmt.setString(3,dpt);
stmt.setString(4,dpt);
}else{
stmt.setInt(3,-1);
stmt.setInt(4,-1);
}
rs = stmt.executeQuery();
if (rs.next()) {
projectId = rs.getString("id");
}
} catch (Exception e) {
ConnTool.getLogger().info(e.getMessage(), e);
}