如何在JSP頁面顯示mysql資料庫內容 (二)

來源:互聯網
上載者:User

標籤: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資料庫內容 (二)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.