PreparedStatement的问题
大家看看这段代码:
//判断用户是否合法的方法,返回boolean值
public boolean isLogin(TeacherVo tv){
//上面的TeacherVo是Vo,包含id,name,password属性.
//且tv.id= 'test ',tv.password= 'test '
boolean flag=false;
DbConnection dbc=new DbConnection();
Connection conn=dbc.getConnection();
PreparedStatement pst=null;
ResultSet rs=null;
String sql= "select * from teacher where id=? and password=? ";
try{
pst=conn.prepareStatement(sql);
String id=tv.getId();
pst.setString(1,id);
String password=tv.getPassword();
pst.setString(2,password);
rs=pst.executeQuery();
if(rs.next())
{
flag=true;
tv.setName(rs.getString( "name "));
System.out.println(tv.getName());
}
rs.close();
pst.close();
}catch(Exception e){
System.out.println( "错误 in TeacherDaoImpl ");
}finally{
dbc.close();
}
return flag;
}
上面的代码flag返回false值,且没抛出异常,而下面的代码却返回true值,为什么?
public boolean isLogin(TeacherVo tv){
//上面的TeacherVo是Vo,包含id,name,password属性
boolean flag=false;
DbConnection dbc=new DbConnection();
Connection conn=dbc.getConnection();
PreparedStatement pst=null;
ResultSet rs=null;
//用不带参数的sql组织PreparedStatement
String sql=
"select * from teacher where id= 'test ' and password= 'test ' ";
try{
pst=conn.prepareStatement(sql);
rs=pst.executeQuery();
if(rs.next())
{
flag=true;
tv.setName(rs.getString( "name "));
System.out.println(tv.getName());
}
rs.close();
pst.close();
}catch(Exception e){
System.out.println( "错误 in TeacherDaoImpl ");
}finally{
dbc.close();
}
return flag;
}
这两个程序应该是一样的,为什么结果不同?
[解决办法]
我晕 你第2个里面的sql
select * from teacher where id= 'test ' and password= 'test '
不和前面的一样吧
select * from teacher where id=? and password=?
[解决办法]
建议你try之前,把tv对象里面的两个属性打出来看看,估计是Null的