標籤:jdbc mysql jsp eclipse tomcat
用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>
顯示結果如下所示:
如何在JSP頁面顯示mysql資料庫內容 (二)