Servlet上連線資料庫的小案例
阿新 • • 發佈:2018-12-21
使用的是mysql資料庫;
在test資料庫下建立一個名為user的表,如果:
訪問資料庫:
建立一個servlet檔案,內容如下:
package com.servlets; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.jasper.tagplugins.jstl.core.Out; import java.sql.*; /** * Servlet implementation class LoginValidate */ @WebServlet(name="LoginValidate", value="/LoginValidate") public class LoginValidate extends HttpServlet { private static final long serialVersionUID = 1L; // JDBC 驅動名及資料庫 URL static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; static final String DB_URL = "jdbc:mysql://localhost:3306/test"; // 資料庫的使用者名稱與密碼,需要根據自己的設定 static final String USER = "root"; static final String PASS = "123456"; /** * @see HttpServlet#HttpServlet() */ public LoginValidate() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doPost(request, response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub Connection conn = null; Statement stmt = null; // 設定響應內容型別 response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); String title = "Servlet Mysql 測試 - 菜鳥教程"; String docType = "<!DOCTYPE html>\n"; out.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" + "<body bgcolor=\"#f0f0f0\">\n" + "<h1 align=\"center\">" + title + "</h1>\n"); try{ // 註冊 JDBC 驅動器 Class.forName("com.mysql.jdbc.Driver"); // 開啟一個連線 conn = DriverManager.getConnection(DB_URL,USER,PASS); // 執行 SQL 查詢 stmt = conn.createStatement(); String sql; sql = "SELECT * FROM user"; ResultSet rs = stmt.executeQuery(sql); // 展開結果集資料庫 while(rs.next()){ // 通過欄位檢索 int id = rs.getInt("userid"); String name = rs.getString("username"); String pwd = rs.getString("password"); // 輸出資料 out.println("userID: " + id); out.println(",username: " + name); out.println(", password: " + pwd); out.println("<br />"); } out.println("</body></html>"); // 完成後關閉 rs.close(); stmt.close(); conn.close(); } catch(SQLException se) { // 處理 JDBC 錯誤 se.printStackTrace(); } catch(Exception e) { // 處理 Class.forName 錯誤 e.printStackTrace(); }finally{ // 最後是用於關閉資源的塊 try{ if(stmt!=null) stmt.close(); }catch(SQLException se2){ } try{ if(conn!=null) conn.close(); }catch(SQLException se){ se.printStackTrace(); } } } }