一个实现JDBC的小程序

<%@ page contentType="text/html" pageEncoding="GBK" language="java"%>
<%@ page import="java.util.*"%>
<%@ page import="java.sql.*"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>

<body>
<%!
//定义数据库驱动程序
public static final String DBDRIVER = "org.gjt.mm.mysql.Driver";
//数据库链接地址
public static final String DBURL = "jdbc:mysql://localhost:3306/student";
public static final String DBUSER = "root";
public static final String DBPASS = "*****";
%>
<%
Connection conn
= null;//声明数据库连接对象
PreparedStatement pstmt
= null;//声明数据库操作
ResultSet rs
= null;//声明数据库结果集
%>
<%
try{
Class.forName(DBDRIVER);
//数据库驱动程序加载
conn
= DriverManager.getConnection(DBURL, DBUSER, DBPASS);//取得数据库连接
String sql = "SELECT stu_no, stu_name, sex, province, AREA FROM stuinfo";
pstmt
= conn.prepareStatement(sql);
rs
= pstmt.executeQuery();//执行查询操作
%>
<center>
<table border="1" width="80%">
<tr>
<td>学号</td>
<td>姓名</td>
<td>性别</td>
<td>省份</td>
<td>市区</td>
</tr>
<%
while(rs.next()){
String stu_no = rs.getString(1);
System.out.println(
"学号" + stu_no);
String stu_name = rs.getString(2);
String sex = rs.getString(3);
String province = rs.getString(4);
String area = rs.getString(5);
%>
<tr>
<td><%=stu_no%></td>
<td><%=stu_name%></td>
<td><%=sex%></td>
<td><%=province%></td>
<td><%=area%></td>
</tr>
<%
}
%>
</table>
</center>
<%
}catch(Exception e){
System.out.println(e);
/*******打印到tomcat中*******/
}finally{
rs.close();
pstmt.close();
conn.close();
}
%>
</body>
</html>

posted @ 2011-10-14 16:39  lihui_yy  阅读(313)  评论(0编辑  收藏  举报