Java連接MySQL數據庫后,我們可以將數據庫中的數據傳遞給HTML頁面進行展示。下面是一個簡單的示例:
import java.sql.*; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class ExampleServlet extends HttpServlet { protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); String dbUrl = "jdbc:mysql://localhost:3306/mydb"; String dbUser = "root"; String dbPass = "password"; try { Class.forName("com.mysql.jdbc.Driver"); Connection conn = DriverManager.getConnection(dbUrl, dbUser, dbPass); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * FROM mytable"); out.println(""); out.println("MySQL Data "); out.println(""); while(rs.next()) { out.println("" + rs.getString("col1") + " - " + rs.getString("col2") + "
"); } out.println(""); rs.close(); stmt.close(); conn.close(); } catch(Exception e) { e.printStackTrace(); } finally { out.close(); } } }
上面的代碼會取出MySQL中mydb庫中的mytable表中的所有數據,并將每行數據的col1和col2作為一段HTML顯示在頁面上。