statement执行参数化的sql语句查不出结果
软件环境:eclipse
数据库:oracle 11.1.0*
package nantian.com.loginServlet; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class loginServlet extends HttpServlet{ public void doPost(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException{ String username = req.getParameter("username"); String password = req.getParameter("password"); Connection connection = null; PreparedStatement statement = null; ResultSet resultset = null; PrintWriter out = res.getWriter(); try { Class.forName("oracle.jdbc.driver.OracleDriver"); String url = "jdbc:oracle:thin:@localhost:1521:orcl"; String user = "kflearn"; String password2 = "kflearn"; connection = DriverManager.getConnection(url, user, password2); //此语句能查处结果 /* String sql = "select count(user_id) from manager_user where user_name = 'ntyzzhi'" + " and user_pass= '12345' ";*/ //这一条执行成功。 /* String sql = "select count(user_id) from manager_user where user_name ='"+ username + "' and user_pass='" + password + "'"; */ //这条语句查不出结果,为何?? String sql = "select count(user_id) from manager_user where user_name = ?" + " and user_pass= ? "; statement = connection.prepareStatement(sql); //username 和 password值是 “ntyzzhi” 、”12345“ 查不出,为何???? statement.setString(1,"ntyzzhi"); statement.setString(2,"12345"); resultset = statement.executeQuery(); System.out.println(sql); if(resultset.next()){ int count = resultset.getInt(1); System.out.println(count); if(count > 0){ out.print("hello : " + username); }else{ out.print("soryy : " + username); } } } catch (Exception e) { e.printStackTrace(); }finally{ try { if (resultset != null) { resultset.close(); } } catch (Exception e2) { e2.printStackTrace(); } try { if (statement != null) { statement.close(); } } catch (Exception e2) { e2.printStackTrace(); } try { if (connection != null) { connection.close(); } } catch (Exception e2) { e2.printStackTrace(); } } } }
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
恩,好的,我再优化一下,谢谢您!
改善一下finally 中的if (xx != null) 判断:将 try catch 放在 if 判断里面
引用来自“yong230”的评论
肯定查不出啊,刚学java吧,字符串类型都得加单引号的
是啊,初学的,这个单引号怎么添加呢?还请您给我写以下,我现在不知道怎么添加!谢谢您!
我已经找到问题了,是因为我数据库里面的字段类型是char类型,是存入的值有空格,所以查询不出。使用语句查询的时候可能会去掉空格。
肯定查不出啊,刚学java吧,字符串类型都得加单引号的