使用jsp运用mysql数据库时遇到的问题

本文介绍了一段JSP代码中查询结果始终为空的原因及其解决方案。主要问题在于字符串编码转换不当导致的数据不匹配,通过正确地进行字符集转换解决了这一问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

   在成功链接数据库后,写好了正确的sql语句,但是在获取结果时总是空?终于找到原因了....

   代码如下:

<body>
  <%!
   public static final String DBDRIVER = "com.mysql.jdbc.Driver";
   public static final String DBURL = "jdbc:mysql://localhost:3308/userinfo";
   public static final String DBUSER = "root";
   public static final String DBPASS  = "mysql";
  %>
    <%
  //接收用户名和密码,完成对用户的验证
  String u = request.getParameter("username");//这个是从之前的一个jsp页面获取的传过来的参数
  String p = request.getParameter("password");
  u = new String (u.getBytes("ISO-8859-1"),"UTF-8");//这句话是之所以总是查询结果为空的主要原因,只有将获取过来的参数成功转化,才能匹配数据库中的内容
  //到数据库中去验证
  Connection conn = null;
  PreparedStatement pstmt = null;
  ResultSet rs = null;
  try{
   Class.forName(DBDRIVER);
   conn = DriverManager.getConnection(DBURL,DBUSER,DBPASS);
   String sql = "select user_pwd from uinfo where user_name = '"+u+"'";
   pstmt = conn.prepareStatement(sql);
   rs = pstmt.executeQuery();
   if(rs.next()){
   
   //说明用户名存在
   if(rs.getString(1).equals(p)){
    //用户一定合法
    response.sendRedirect("demo03.jsp");
   }else{
    //密码错误
    response.sendRedirect("demo01.jsp?errNo=1");
   }
  }else{
    //说明用户名出错
    response.sendRedirect("demo01.jsp?errNo=2");
   }
  }catch(Exception e){
   System.out.println(e);
  }finally{
   rs.close();
   pstmt.close();
   conn.close();
  }
  
  
  
  
  //验证,先不到数据库去验证,就简单验证
  /*if(u.equals("jxs")&&p.equals("1")){
   //合法,跳转 demo03.jsp

   response.sendRedirect("demo03.jsp");
  } else{
   //不合法,跳转到demo01.jsp
   response.sendRedirect("demo01.jsp");
  }  */
  
    %>
  </body>

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值