日期:2014-05-17  浏览次数:20693 次

求教:如何验证用户名存在
我想实现登录时验证用户名是否存在于数据库,如果不在count为0的话抛出异常。求指点。应该还有错的地方,请宽容菜鸟的无知。

Connection conn = DBUtils.getConnection();

String queryUN = "SELECT count(1) FROM my_user where username=?";
PreparedStatement pstmt = conn.prepareStatement(queryUN);

 
  if( ){
  throw new Exception("账号名不存在");
  }
}


------解决方案--------------------
ResultSet rs = null;
rs = pstmt.executeQuery();

int j=0;
while (rs.next()) {
 j=1;
}



if(j==0){
throw new Exception("账号名不存在");
}
------解决方案--------------------
String userName = ...
Connection conn = DBUtils.getConnection();
ResultSet rs = null;
String queryUN = "SELECT count(1) FROM my_user where username=?";
PreparedStatement pstmt = conn.prepareStatement(queryUN);
pstmt.setString(1,userName);
rs = pstmt.executeQuery();

  
 if(rs.next() ){
if ( rs.getInt(1) == 0) ) {
throw new Exception("账号名不存在");
}
 } 

------解决方案--------------------
Java code


public Boolean queryUser() throws Exception{
Connection conn = DBUtils.getConnection();
String queryUN = "SELECT count(1) FROM my_user where username=?";
preparedstatement pstmt = conn.preparestatement(queryUN);
pstmt.setstring(1,"放你要查的用户名");
resultset rs = pstmt.executequery();

if(rs.next()){
System.out.print("用户名存在");
return true;
}
else
{
System.out.print("账号名不存在");
return false;
}
rs.close();
pstmt.close();
conn.close();
}