本教程假定您已經(jīng)了解了 JDBC 應用程序的工作方式。在您開始學習 Servlet 數(shù)據(jù)庫訪問之前,請確保您已經(jīng)有適當?shù)?JDBC 環(huán)境設置和數(shù)據(jù)庫。
從基本概念下手,讓我們來創(chuàng)建一個簡單的表,并在表中創(chuàng)建幾條記錄。
在測試數(shù)據(jù)庫 TEST 中創(chuàng)建 Employees 表,請按以下步驟進行:
打開命令行提示符(Command Prompt),并更改進入到安裝目錄,如下所示:
C:\> C:\>cd Program Files\MySQL\bin C:\Program Files\MySQL\bin>
登錄到數(shù)據(jù)庫,如下所示:
C:\Program Files\MySQL\bin>mysql -u root -p Enter password: ******** mysql>
在測試數(shù)據(jù)庫 TEST 中創(chuàng)建 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 表中創(chuàng)建幾條記錄,如下所示:
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 數(shù)據(jù)庫。
// 加載必需的庫
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 驅(qū)動器名稱和數(shù)據(jù)庫的 URL
static final String JDBC_DRIVER="com.mysql.jdbc.Driver";
static final String DB_URL="jdbc:mysql://localhost/TEST";
// 數(shù)據(jù)庫的用戶名與密碼,需要根據(jù)自己的設置
static final String USER = "root";
static final String PASS = "password";
// 設置響應內(nèi)容類型
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "數(shù)據(jù)庫結果";
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{
// 注冊 JDBC 驅(qū)動器
Class.forName("com.mysql.jdbc.Driver");
// 打開一個連接
Connection conn = DriverManager.getConnection(DB_URL,USER,PASS);
// 執(zhí)行 SQL 查詢
Statement stmt = conn.createStatement();
String sql;
sql = "SELECT id, first, last, age FROM Employees";
ResultSet rs = stmt.executeQuery(sql);
// 展開結果集數(shù)據(jù)庫
while(rs.next()){
// 通過字段檢索
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString("last");
// 輸出數(shù)據(jù)
out.println("ID: " + id + "<br>");
out.println(", Age: " + age + "<br>");
out.println(", First: " + first + "<br>");
out.println(", Last: " + last + "<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();
}
}
}
}
現(xiàn)在讓我們來編譯上面的 Servlet,并在 web.xml 文件中創(chuàng)建以下條目:
....
<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>
....
現(xiàn)在調(diào)用這個 Servlet,輸入鏈接:http://localhost:8080/DatabaseAccess,將顯示以下響應結果:
數(shù)據(jù)庫結果 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
更多建議: