本文實例講述了Java實作JSP使用Servelt連接Oracle資料庫的方法。為了實作在Servlet 中連接資料庫,必須編寫Servlet 的類別程式。將Servlet 類別程式放到WEB 伺服器的servlets 或classes 目錄下面,為呼叫Servlet,需要建立發送Servlet 請求的HTML 文件。本例透過(Driver)Class.forName(driverName).newInstance()方法來實作載入驅動程序,建立與資料庫連線。
具體程序代碼為:
1. Database 類別繼承了HttpServlet 類,共有兩個方法:doGet()和displayResult(),程式碼如下:
public class Database extends HttpServlet{public void doGet();public void displayResult(ResultSet results,PrintWriter out);}
2.在doGet()方法中建立與資料庫的連線並執行查詢:
public void doGet(){HttpServletRequest request,HttpServletResponse response}throws ServletException, IOException{PrintWriter out;String title = "Simple Servlet connecting to Oracle DB";response out;String title = "Simple Servlet connecting to Oracle DB";response。 response.getWriter();out.println("<HTML><HEAD><TITLE>");out.println(title);out.println("</TITLE></HEAD><BODY>");out .println("<H1>" + title + "</H1>");out.println("<P>This is output from SimpleServlet.");String driverName = "oracle.jdbc.driver.OracleDriver";Driver d;Connection con;Statement stmt;ResultSet results;try{d = (Driver)Class.forName(driverName).newInstance();con = DiverManager.getConnection("jdbc:oracle:thin:ndb/[email protected]:1521:PC6");stmt = con.createStatement();String sqlstr = "select * from data";results = stmt.executeQuery(sqlstr);displayResult(results,out);stmt.close();con.close();}catch (Exception e){out.println("error: " + e.toString());} out.println("</BODY></HTML>");out.close();}
3. DisplayResult()方法顯示查詢結果:
public void displayResult(ResultSet results,PrintWriter out){StringBuffer buf = new StringBuffer();String temp;try{ResultSetMetaData rsmd = results.getMetaData();int numCols = rs。 (i=1; i <= numCols; i++){if (i > 1) buf.append(",");buf.append(rsmd.getColumnLabel(i));}buf.append("");while (results.next() && rowcount < 100 ){for (i=1; i <= numCols; i++){if (i > 1) buf.append(",");buf.append((results.getString(i)));}buf.append("<br>");rowcount++;}out.println("<br>");out .println(buf.toString());results.close();}catch (Exception e){out.println("error: " + e.toString());return;}}
4.因為程式使用了JDBC 類別、servlet 類別和使用控制台輸出,所以需要引入如下的套件:
import java.sql.*;import java.io.*;import javax.servlet.*;import javax.servlet.http.*;
5.編譯Database.java,產生Database.class 文件,將Database.class 放到WEB 伺服器的servlets 目錄下,本例採用Java Web Server 作為WEB 伺服器。配置WEB 伺服器,新增database.class,指定名稱為database。
6.編寫呼叫Servlet 的database.html 檔案。程式碼如下:
<html><head><title>Jsp使用Servlet連接資料庫</title></head><body><center><form action="/servlet/database" method="get"><input name="action " type="submit" value="連接資料庫"></form></center></body></html>