用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;
- 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>
顯示結果如下所示:
