做一个登录的页面,数据库中的登录者不存在,可是返回的是一个非null的用户类。我的用户类中有部分字段类型是int型的,在数据库中查找不存在用户时会默认给int型字段赋值0,如何解决此类问题?难道非要在查找方法中去判断每个字段吗?
/**
* 根据用户名查找用户信息
*/
public User findUserByName(String userName)
{
User user=new User();
con=getConnection();
try {
pstmt=con.prepareStatement("select * from TBL_USER where userName=?");
pstmt.setString(1, userName);
rs=pstmt.executeQuery();
if(rs!=null)
{
while(rs.next())
{
user.setUId(rs.getInt(1));
user.setUserName(rs.getString(2));
user.setUserPass(rs.getString(3));
user.setStatusId(rs.getInt(4));
}
}
} catch (SQLException e) {
e.printStackTrace();
}
finally
{
closeAll();
}
return user;
}
请高手指点,在线等,谢谢!
/**
* 根据用户名查找用户信息
*/
public User findUserByName(String userName)
{
User user=new User();
con=getConnection();
try {
pstmt=con.prepareStatement("select * from TBL_USER where userName=?");
pstmt.setString(1, userName);
rs=pstmt.executeQuery();
if(rs!=null)
{
while(rs.next())
{
user.setUId(rs.getInt(1));
user.setUserName(rs.getString(2));
user.setUserPass(rs.getString(3));
user.setStatusId(rs.getInt(4));
}
}
} catch (SQLException e) {
e.printStackTrace();
}
finally
{
closeAll();
}
return user;
}
请高手指点,在线等,谢谢!
把User user=new User(); 放至while(rs.next())循环体的第一部分。那方法的返回值应该是个容器类型了。
没有用户时返回user非null,应该是你 User user=new User(); 这里new了。
/**
* 根据用户名查找用户信息
*/
public User findUserByName(String userName)
{
User user=null;
con=getConnection();
try {
pstmt=con.prepareStatement("select * from TBL_USER where userName=?");
pstmt.setString(1, userName);
rs=pstmt.executeQuery();
while(rs.next())
{
user=new User();
user.setUId(rs.getInt(1));
user.setUserName(rs.getString(2));
user.setUserPass(rs.getString(3));
user.setStatusId(rs.getInt(4));
}
} catch (SQLException e) {
e.printStackTrace();
}
finally
{
closeAll();
}
return user;
}