看看下面的代码哪里错了,为什么得到的结果不一样?//使用Statement测试
public class DBUtil1 {
// 构造函数
public DBUtil1(){ } // 登录验证
public String getUser(String userID,String userPass){
// 声明一字符,用来返回用户类型
String userType = null;
// 声明一查询语句
String sql = "select USER_ROLE from user_info where USER_ID = '" + userID + "' and USER_PASS = '" + userPass + "'";
// 声明一Connection
Connection conn = null;
// 声明一statement
Statement st = null;
// 声明一resultSet
ResultSet rs = null;
try{
// 建立连接
conn = DBConnect.getConnection();
//创建一statement对象
st = conn.createStatement();
// 执行查询操纵,得到结果集
rs = st.executeQuery(sql);
// 判断该登录用户是否存在
while (rs.next()){
// 当前用户存在
userType = rs.getString(1);
} rs.close();
st.close();
conn.close();
} catch (Exception e){
e.printStackTrace();
// System.out.println();
}
return userType;
}
}//使用PreparedStatement测试
public class DBUtil {
// 构造函数
public DBUtil(){ } // 登录验证
public String getUser(String userID,String userPass){
// 声明一字符,用来返回用户类型
String userType = null;
// 声明一查询语句
String sql =
 "select USER_ROLE from user_info where USER_ID = ? and USER_PASS = ? ";
// 声明一Connection
Connection conn = null;
// 声明一prestatement
PreparedStatement pstmt = null;
//Statement st = null;
// 声明一resultSet
ResultSet rs = null;
try{
// 建立连接
conn = DBConnect.getConnection();
// 获取一个preparedStatement对象
pstmt = conn.prepareStatement(sql);
// 设定该对象总的参数
 pstmt.setString(1,userID);
 pstmt.setString(2,userPass);
// 执行查询操纵,得到结果集
rs = pstmt.executeQuery();
// 判断该登录用户是否存在
while (rs.next()){
// 当前用户存在
userType = rs.getString(1);
System.out.println(userType);
} rs.close();
pstmt.close();
//st.close();
conn.close();
} catch (Exception e){
e.printStackTrace();
// System.out.println();
}
return userType;
}
}测试类public class Test {
public static void main(String args[]){
String userType = null;
//使用PreparedStatement测试
DBUtil dbutil = new DBUtil();
//使用Statement测试
//DBUtil1 dbutil = new DBUtil1();
userType = dbutil.getUser("WELL","123456");
System.out.println(userType);
}
}问题:使用Statement可以得到正常结果,但是PreparedStatement得到错误结果。大家看看是PreparedStatement哪个地方有问题!谢谢先

解决方案 »

  1.   

    问题补充,使用的数据库为Oracle11gr2,JDBC驱动为OJDBC14.JAR
      

  2.   

    pstmt.setString(1,userID);
    应该没有什么问题,如果有也是参数类型不正确
      

  3.   


    数据库中参数为char型
    参数类型为String
    应该不会是这个问题吧!
      

  4.   


    用statement可以得到用户的类型,
    而用PreparedStatement的到用户类型为null。这个明显是错误的!
      

  5.   

    debug,把sql 文打印出来,然后用工具执行,看看能不能查询出数据
      

  6.   

    PreparedStatement的sql打印出来是这个样子:select USER_ROLE from user_info where USER_ID = ? and USER_PASS = ?
    感觉是没有赋值成功!
    UP!!!!
      

  7.   

    对于varchar,使用like,别用"="
    USER_ROLE from user_info where USER_ID = ? and USER_PASS like ?
      

  8.   

    like应该是模糊查询吧,不对吧!
      

  9.   


    数据库中参数为char型
    参数类型为String
    应该不会是这个问题吧!很明显就是这里出问题了,因为char有空格,lz不妨把sql的那个char的字段先trim后再对比