在jsp页面上显示数据库中的数据-(一)
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@page import=".*"%>
<%--导入java.sql包--%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http:///TR/html4/">
<html>
<head>
<title>从db_book数据库中读出book表</title>
</head>
<body>
<center>
<%
try {
Class.forName(""); 驱动程序名
String url = "jdbc:mysql://localhost:3306/db_book?characterEncoding=utf8&useSSL=false&serverTimezone=UTC&rewriteBatchedStatements=true"; //数据库名
String username = "root"; //数据库用户名
String password = "root"; //数据库用户密码
Connection conn = DriverManager.getConnection(url, username, password); //连接状态
System.out.println("数据库连接成功!");
%>
<table border="2">
<tr>
<th>序号</th>
<th>书名</th>
<th>作者</th>
<th>出版社</th>
<th>出版时间</th>
<th>价格</th>
<th>ISBN号</th>
</tr>
<%
Statement stmt = null;
ResultSet rs = null;
String sql = "SELECT * FROM book;"; //查询语句
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
out.print("查询结果:");
out.print("<br/>");
while (rs.next()) {
%>
<tr>
<td><%=rs.getInt("id")%></td>
<td><%=rs.getString("bookname")%></td>
<td><%=rs.getString("author")%></td>
<td><%=rs.getString("press")%></td>
<td><%=rs.getDate("pubdate")%></td>
<td><%=rs.getFloat("price")%></td>
<td><%=rs.getString("isbn")%></td>
</tr>
<%
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("数据库连接失败");
}
%>
</center>
</body>
</html>