日期:2014-05-20  浏览次数:20792 次

请教各位大侠,数据库查询语句没有返回值如何处理?
请教各位高手,我要用数据库判断用户登录表单验证,根据用户名拿到密码并比较select * from user where username='"+username+"'",如果正确,就执行下面操作,但是如果查询时,数据库里没有这个用户名,就会报错,怎么解决这个错误?用那个方法可以判断这个错误?我的代码如下:
[code=Java][/code]public class Control {
public User checkUser(String username){
String sql = "select * from user where username='"+username+"'";
Connection conn=dbUtil.getConnection();
Statement stmt=dbUtil.getStmt(conn);
ResultSet rs=dbUtil.getRs(stmt, sql);
String password = null;
User user = null; 
String level = null;
try {
if(rs.next()){
password = rs.getString("password");
level = rs.getString("level");
user = new User(username,password,level);
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
dbUtil.closeRs(rs);
dbUtil.closeStmt(stmt);
dbUtil.closeConn(conn);
}
return user;
}
--------------------------------------------------------
public class showService extends HttpServlet {
Control ct = new Control();
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
req.setCharacterEncoding("gbk");
resp.setCharacterEncoding("gbk");
String username = req.getParameter("username");
String password = req.getParameter("password");
User user = ct.checkUser(username);
/*调用Control里的方法,验证权限,如果权限为1,-->经理跳到经理页面
如果权限是2,-->助理跳到助理页面,如果权限是3,普通员工,跳到员工页面。*/
String level = user.getLevel();//这是是调用方法得到权限返回值
if(password.equals(user.getPassword())){
if("1".equals(level)){
resp.sendRedirect("Manager.jsp");
}else if("2".equals(level)){
System.out.println("你好!");
req.getRequestDispatcher("Assistant.jsp").forward(req, resp);
}else if("3".equals(level)){
req.getRequestDispatcher("Personnel.jsp").forward(req, resp);
}
}else{
System.out.println("用户名密码错误");
}
}

------解决方案--------------------

如果数据库中不存在这个用户名
ResultSet rs=dbUtil.getRs(stmt, sql);
rs就会为空,所以LZ要判断一下了!