用JavaBean实现数据库的连接和关闭,在jsp页面输出数据库中student表中学生的信息
package com.hanqi.test; import java.sql.*; public class XveSheng { Connection conn; Statement st; ResultSet rs; public Connection getConn() { return conn; } public void setConn(Connection conn) { this.conn = conn; } public Statement getSt() { return st; } public void setSt(Statement st) { this.st = st; } public ResultSet getRs() { return rs; } public void setRs(ResultSet rs) { this.rs = rs; } public void lianjie() { try { Class.forName("oracle.jdbc.driver.OracleDriver"); String strUrl = "jdbc:oracle:thin:@localhost:1521:orcl" ; conn = DriverManager.getConnection(strUrl, "test", "5211314"); System.out.println("连接数据库成功!"); } catch (Exception e) { e.printStackTrace(); } } public void guanbi() { try { conn.close(); st.close(); rs.close(); } catch (SQLException e) { e.printStackTrace(); } } }
<%@page import="com.hanqi.test.XveSheng"%> <%@page import="java.sql.*"%> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>学生信息</title> </head> <body> <div align="center"><font size="20px">学生信息表</font></div> <table border="1" cellspacing="0" width="80%" align="center" style="text-align: center"> <tr> <td height="40">学号</td> <td >姓名</td> <td >性别</td> <td >生日</td> <td>班级</td> </tr> <%
try{ XveSheng xs = new XveSheng(); xs.lianjie(); xs.setSt(xs.getConn().createStatement()); xs.setRs(xs.getSt().executeQuery("select * from student")); while(xs.getRs().next()) { String sno = xs.getRs().getString(1); String sname = xs.getRs().getString(2); String ssex = xs.getRs().getString(3); Date sbirthday= xs.getRs().getDate(4); String sclass = xs.getRs().getString(5); %> <tr> <td height="40"><%=sno %></td> <td ><%=sname %></td> <td ><%=ssex %></td> <td ><%=sbirthday.toString() %></td> <td><%=sclass %></td> </tr> <% } xs.guanbi();
}
catch(Exception e)
{
}
%> </table> </body> </html>