用Eclipse tomcat新建一个JSP页面(一)介绍了如何创建一个web程序和第一个jsp页面,以及Eclipse需要的一些必要配置。今天,我们重点说一下如何从数据库中查询数据,并且在JSP页面显示。
首先需要注意这样一个问题:
建的如果是Java项目,只需要引入MySQL-connector-java-5.1.10-bin.jar就可以运行java项目。建的如果是web工程,当Class.forName("com.mysql.jdbc.Driver");时,Eclipse是不会去查找字符串,不会去查找驱动。所以需要把mysql-connector-java-5.1.10-bin.jar拷贝到tomcat下lib目录下,然后,右键【工程】,点击【properties】,然后点击【Java Build Path】,点击【Add External Jars...】,从tomcat下lib目录中选择对应的mysql-connector-java-5.1.10-bin.jar,如下图所示,然后点击【OK】即可。
否则,控制台会报错: java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
显示数据库数据的jsp代码如下:
- <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;
- 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>