2016-06-13 · 百度知道合伙人官方认证企业
在数据库提取部分数据,在JSP上显示的做法如下:
思路:1、创建db连接 2、创建statement 3、执行查询 4、遍历结果并展示
完整代码如下:
<span style="font-size:12px;"><span style="font-size:14px;"><%@ page language="java" import="java.sql.*,java.io.*,java.util.*"%>
<%@ page contentType="text/html;charset=utf-8"%>
<html>
<head>
<style type="text/css">
table {
border: 2px #CCCCCC solid;
width: 360px;
}
td,th {
height: 30px;
border: #CCCCCC 1px solid;
}
</style>
</head>
<body>
<%
//驱动程序名
String driverName = "com.mysql.jdbc.Driver";
//数据库用户名
String userName = "root";
//密码
String userPasswd = "szy";
//数据库名
String dbName = "studentmanage";
//表名
String tableName = "student";
//联结字符串
String url = "jdbc:mysql://localhost:3306/" + dbName + "?user="
+ userName + "&password=" + userPasswd;
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection connection = DriverManager.getConnection(url);
Statement statement = connection.createStatement();
String sql = "SELECT * FROM " + tableName;
ResultSet rs = statement.executeQuery(sql);
%>
<br>
<br>
<table align="center">
<tr>
<th>
<%
out.print("学号");
%>
</th>
<th>
<%
out.print("姓名");
%>
</th>
<th>
<%
out.print("专业");
%>
</th>
<th>
<%
out.print("班级");
%>
</th>
</tr>
<%
while (rs.next()) {
%>
<tr>
<td>
<%
out.print(rs.getString(1));
%>
</td>
<td>
<%
out.print(rs.getString(2));
%>
</td>
<td>
<%
out.print(rs.getString(3));
%>
</td>
<td>
<%
out.print(rs.getString(4));
%>
</td>
</tr>
<%
}
%>
</table>
<div align="center">
<br> <br> <br>
<%
out.print("数据查询成功,恭喜你");
%>
</div>
<%
rs.close();
statement.close();
connection.close();
%>
</body>
</html></span><span style="font-size:24px;color: rgb(255, 0, 0);">
</span></span>
展示结果:
import="java.sql.*"
pageEncoding="GBK"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GBK">
<title>上海方捷信息技术有限公司-在线测试-考试成绩</title>
</head>
<body bgcolor="#cccccc">
<br>
<%
Connection conn=null;
Statement stmt=null;
ResultSet rs=null;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
conn=DriverManager.getConnection("jdbc:odbc:test");
String sql="select * from score";
stmt=conn.createStatement();
rs=stmt.executeQuery(sql);
%>
<table align="center" border="1" bgcolor="pink">
<th>姓名</th>
<th>科目</th>
<th>分数</th>
<th>评语</th>
<%
while(rs.next()){
String name=rs.getString("name");
String type=rs.getString("type");
String score=rs.getString("score");
String comment=rs.getString("comment");
%>
<tr align="center">
<td> <%=name %></td>
<td> <%=type %></td>
<td> <%=score %></td>
<td> <%=comment %></td>
</tr>
<%
}
%>
</table>
</body>
</html>