- Servlet 教程
- Servlet - 主頁
- Servlet - 簡介
- Servlet - 環境設定
- Servlet - 生命週期
- Servlet - 示例
- Servlet - 表單資料
- Servlet - 客戶端請求
- Servlet - 伺服器響應
- Servlet - Http 程式碼
- Servlet - 編寫過濾器
- Servlet - 異常
- Servlet - 處理 Cookie
- Servlet - 跟蹤會話
- Servlet - 資料庫訪問
- Servlet - 上傳檔案
- Servlet - 處理日期
- Servlet - 網頁重定向
- Servlet - 計數器命中
- Servlet - 自動重新整理
- Servlet - 傳送電子郵件
- Servlet - 打包
- Servlet - 除錯
- Servlet - 國際化
- Servlet - 註釋
- Servlet 實用資源
- Servlet - 問答
- Servlet - 快速指南
- Servlet - 實用資源
- Servlet - 討論
Servlet - 資料庫訪問
本教程假定你已瞭解 JDBC 應用程式如何執行。在開始透過 servlet 訪問資料庫之前,請確保正確設定了 JDBC 環境和資料庫。
有關如何使用 JDBC 及其環境設定訪問資料庫的更多詳細資訊,你可以檢視我們的 JDBC 教程。
從基本概念開始,我們建立一個簡單的表格並在表格中建立一些記錄,如下所示:
建立表格
要在 TEST 資料庫中建立 Employees 表,請使用下列步驟:
步驟 1
開啟 命令提示符 並更改為安裝目錄,如下所示:
C:\> C:\>cd Program Files\MySQL\bin C:\Program Files\MySQL\bin>
步驟 2
登入資料庫,如下所示:
C:\Program Files\MySQL\bin>mysql -u root -p Enter password: ******** mysql>
步驟 3
在 TEST 資料庫中建立名為 Employee 的表格,如下所示:
mysql> use TEST; mysql> create table Employees ( id int not null, age int not null, first varchar (255), last varchar (255) ); Query OK, 0 rows affected (0.08 sec) mysql>
建立資料記錄
最後,在 Employee 表中建立一些記錄,如下所示:
mysql> INSERT INTO Employees VALUES (100, 18, 'Zara', 'Ali'); Query OK, 1 row affected (0.05 sec) mysql> INSERT INTO Employees VALUES (101, 25, 'Mahnaz', 'Fatma'); Query OK, 1 row affected (0.00 sec) mysql> INSERT INTO Employees VALUES (102, 30, 'Zaid', 'Khan'); Query OK, 1 row affected (0.00 sec) mysql> INSERT INTO Employees VALUES (103, 28, 'Sumit', 'Mittal'); Query OK, 1 row affected (0.00 sec) mysql>
訪問資料庫
這裡有一個示例,說明如何使用 Servlet 訪問 TEST 資料庫。
// Loading required libraries
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class DatabaseAccess extends HttpServlet{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL="jdbc:mysql:///TEST";
// Database credentials
static final String USER = "root";
static final String PASS = "password";
// Set response content type
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Database Result";
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor = \"#f0f0f0\">\n" +
"<h1 align = \"center\">" + title + "</h1>\n");
try {
// Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
// Open a connection
Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
// Execute SQL query
Statement stmt = conn.createStatement();
String sql;
sql = "SELECT id, first, last, age FROM Employees";
ResultSet rs = stmt.executeQuery(sql);
// Extract data from result set
while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString("last");
//Display values
out.println("ID: " + id + "<br>");
out.println(", Age: " + age + "<br>");
out.println(", First: " + first + "<br>");
out.println(", Last: " + last + "<br>");
}
out.println("</body></html>");
// Clean-up environment
rs.close();
stmt.close();
conn.close();
} catch(SQLException se) {
//Handle errors for JDBC
se.printStackTrace();
} catch(Exception e) {
//Handle errors for Class.forName
e.printStackTrace();
} finally {
//finally block used to close resources
try {
if(stmt!=null)
stmt.close();
} catch(SQLException se2) {
} // nothing we can do
try {
if(conn!=null)
conn.close();
} catch(SQLException se) {
se.printStackTrace();
} //end finally try
} //end try
}
}
現在,讓我們編譯上述 servlet並在 web.xml 中建立以下條目:
.... <servlet> <servlet-name>DatabaseAccess</servlet-name> <servlet-class>DatabaseAccess</servlet-class> </servlet> <servlet-mapping> <servlet-name>DatabaseAccess</servlet-name> <url-pattern>/DatabaseAccess</url-pattern> </servlet-mapping> ....
現在使用 URL https://:8080/DatabaseAccess 呼叫此 servlet,該 URL 將顯示以下響應:
Database Result
ID: 100, Age: 18, First: Zara, Last: Ali ID: 101, Age: 25, First: Mahnaz, Last: Fatma ID: 102, Age: 30, First: Zaid, Last: Khan ID: 103, Age: 28, First: Sumit, Last: Mittal
廣告
