本文實例講述了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.setContentType("text/html;charset=GB2312"); out = 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 = rsmd.getColumnCount(); int i, rowcount = 0; for (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>