采用Prepared Statement的对象实现记录的查询操作 相关代码

<%@ page  contentType="text/html" language="java" import="java.sql.*" pageEncoding="utf-8"%>

<html>
  <head>
    <title>显示所有学生的页面</title>
  </head>
  <body>
   <center>
   <%
   String driver = "com.mysql.jdbc.Driver";
 // URL指向要访问的数据库名test1
 String url = "jdbc:mysql://127.0.0.1:3306/a";
 // MySQL配置时的用户名
 String user = "root";
 // Java连接MySQL配置时的密码
 String password = "root";
 try {
 // 1 加载驱动程序
 Class.forName(driver);
 // 2 连接数据库
 Connection conn = DriverManager.getConnection(url, user, password);
 // 3 用来执行SQL语句
 Statement statement = conn.createStatement();
 // 要执行的SQL语句
 
 String sql="select *from stu_info";
 PreparedStatement pstmt=conn.prepareStatement(sql);
 request.setCharacterEncoding("utf-8");
 ResultSet rs=pstmt.executeQuery();
 rs.last();
 
 int n=pstmt.executeUpdate();
 if(n==1){%>数据插入成功!<br><%}
 else{%>数据插入失败!<br> <%}
 if(pstmt!=null){pstmt.close();}
 if(conn!=null) { conn.close();}
 } catch (ClassNotFoundException e) {
 System.out.println("Sorry,can`t find the Driver!");
 e.printStackTrace();
 } catch (SQLException e) {
 e.printStackTrace();
 } catch (Exception e) {
 e.printStackTrace();
 }
   %>
   你要查询的学生数据表中共有<%String sql="select *from stu_info";
   Connection conn = DriverManager.getConnection(url, user, password);
 PreparedStatement pstmt=conn.prepareStatement(sql);
 request.setCharacterEncoding("utf-8");
 ResultSet rs=pstmt.executeQuery(); %>
   <font size="5" color="red"><%=rs.getRow()%></font>人
   <table border="2"bgcolor="ccceee"width="650">
   <tr bgcolor="CCCCCC"align="center">
   <td>记录条数</td><td>学号</td><td>姓名</td><td>性别</td><td>年龄</td><td>体重</td><td>身高</td></tr>
   <%rs.beforeFirst();
   while(rs.next()) {%><tr align="center">
                          <td><%=rs.getRow()%></td>
                          <td><%=rs.getString("id")%></td>
                           <td><%=rs.getString("name")%></td>
                            <td><%=rs.getString("sex")%></td>
                             <td><%=rs.getString("age")%></td>
                              <td><%=rs.getString("weight")%></td>
                               <td><%=rs.getString("hight")%></td>
                               </tr>
                               <%} %>
                               </table>
   </center>
   <%if(rs!=null){rs.close();}
     if(pstmt!=null){pstmt.close();}
     if(conn!=null){conn.close();}
     %>
  </body>
</html>

 

 

 

注:数据库和数据提交的那篇文章相对应

posted @ 2017-11-12 22:34  红树叶  阅读(279)  评论(0编辑  收藏  举报