Javaweb学习12.8

今天写出了精准查找的方法

通过页面的传过来的两个字符串参数,写好sql语句,通过判断用if语句就可以选择了,避免写多个函数显得比较臃肿

public List<User_Bean> search(String cxfs,String str) throws SQLException{//查询条件方法
String sql=null;
if(cxfs.equals("id")) {sql="select * from user where id like '"+str+"'";}
else if(cxfs.equals("role")) {sql="select * from user where role like '"+str+"'";}
System.out.println(sql);
Connection conn=DBUtil.getConnection();
Statement st=null;
PreparedStatement pt = conn.prepareStatement(sql);
List<User_Bean> list=new ArrayList<>();
ResultSet rs=null;
User_Bean bean=null;
try {
pt=conn.prepareStatement(sql);
rs=pt.executeQuery();
while(rs.next()) {
int id=rs.getInt("id");
String pass = rs.getString("pass");
String role = rs.getString("role");
bean=new User_Bean(id,pass,role);
list.add(bean);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
DBUtil.close(rs, st, conn);
}
return list;
}

原文地址:https://www.cnblogs.com/D10304/p/14155855.html