查询数据库数据并传入servlet
功能:servlet读取前台要查询的值(des),调用查询函数,得到查到的值的列表,再将列表值传到前台显示。
servlet:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { QueryFromMySql queryFromMySql=new QueryFromMySql(); //查询数据库类 request.setCharacterEncoding("utf-8"); //设置读取编码 String des=request.getParameter("des"); //通过des查询 List<CiTiao> ciTiaos=queryFromMySql.SearchByDes(des); System.out.println(ciTiaos.get(0).toString()); int count=queryFromMySql.query(); System.out.println(count); request.setAttribute("citiaos", ciTiaos); //将查询得到的结果传到前台jsp页面 request.getRequestDispatcher("/list_sort.jsp").forward(request, response); }
QueryFormMySql:
private static String DriverName="com.mysql.jdbc.Driver"; private static String UName="root"; private static String Upwd="root"; private static String Url="jdbc:mysql://192.168.25.1:3306/xinjian?useUnicode=true&characterEncoding=UTF-8"; public List<CiTiao> SearchByDes(String des) //根据分类查询所有的词条信息 { List<CiTiao> CiTiaos=new ArrayList<CiTiao>(); CiTiao CiTiao=null; Connection conn=null; PreparedStatement pstmt=null; ResultSet result=null; try { Class.forName(DriverName); conn=DriverManager.getConnection(Url, UName, Upwd); String sql="select * from citiao where des like ?"; pstmt= conn.prepareStatement(sql); pstmt.setString(1,"%"+des+"%"); result=pstmt.executeQuery(); while(result.next()) { String name=result.getString("name"); //词条名称2 des=result.getString("des"); //词条简单内容3 String url=result.getString("url"); //词条链接4 CiTiao=new CiTiao(name,des,url); CiTiaos.add(CiTiao); } return CiTiaos; } catch(ClassNotFoundException e) { e.printStackTrace(); return null; } catch (SQLException e) { e.printStackTrace(); return null; } catch(Exception e) { e.printStackTrace(); return null; } finally { try { if(result!=null) result.close(); if(pstmt!=null) pstmt.close(); if(conn!=null) conn.close(); } catch(SQLException e) { e.printStackTrace(); } } }
相关推荐
Lzs 2020-10-23
聚合室 2020-11-16
零 2020-09-18
Justhavefun 2020-10-22
jacktangj 2020-10-14
ChaITSimpleLove 2020-10-06
Andrea0 2020-09-18
周游列国之仕子 2020-09-15
afanti 2020-09-16
88234852 2020-09-15
YClimb 2020-09-15
风雨断肠人 2020-09-04
卖口粥湛蓝的天空 2020-09-15
stulen 2020-09-15
pythonxuexi 2020-09-06
abfdada 2020-08-26
梦的天空 2020-08-25