本教學假定你已經了解JDBC應用程序的工作方式。通過一個servlet的數據庫訪問開始之前,確保你有適當的JDBC環境的設置和數據庫能正常使用。
對於更詳細關於如何訪問數據庫使用JDBC和環境的設置,可以通過JDBC教學。
基本概念下手,讓我們創建一個簡單的表並創建該表中的記錄數如下:
要在測試數據庫TEST中創建Employees表,請使用下列步驟:
打開命令提示符並更改進入到安裝目錄如下:
C:\> C:\>cd Program Files\MySQL\bin C:\Program Files\MySQL\bin>
登錄到數據庫,如下所示:
C:\Program Files\MySQL\bin>mysql -u root -p Enter password: ******** mysql>
在測試數據庫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訪問的測試數據庫。
// 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://localhost/TEST"; // Database credentials static final String USER = "root"; static final String PASS = "password"; // Set response content type - by www.gitbook.net 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 conn = DriverManager.getConnection(DB_URL,USER,PASS); // Execute SQL query 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: http://localhost:8080/DatabaseAccess將顯示以下回應調用這個servlet結果:
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