Java实现JSP在Servelt中连接Oracle数据库的方法
程序员文章站
2024-02-29 16:53:16
本文实例讲述了java实现jsp使用servelt连接oracle数据库的方法。为了实现在servlet 中连接数据库,必须编写servlet 的类程序。将servlet...
本文实例讲述了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>