本文实例讲述了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/ndb@192.168.1.6: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>