日期:2013-04-23  浏览次数:20471 次

本文以一个完整的JavaBean数据库访问程序简要说明jsp操作数据库。
  本程序由3个bean组成,其中WebConstants中定义全局变量,ConnectionManager管理数据库连接,MainBean利用WebConstants和ConnectionManager操作数据库。

首先定义全局变量,如下:

package WebRelease;

public interface WebConstants
{
  public static final String driverClass ="driverClass";
  const userId is the user id to connect to database
  public static final String userId ="comm";
  const passWd is the user password to connect to database
  public static final String passWd ="comm123";
  const url is the url to connect to database
  public static final String url="jdbc:oracle:thin:@10.2.0.1:1521:ORCL";
  public static final String selectType ="select";
  public static final String connection ="connection";
  public static final String connError ="conError";
}

接着创建一个数据库连接管理bean,如下:

package WebRelease;

import java.io.*;
import java.beans.*;
import java.util.*;
import java.sql.*;
import WebRelease.WebConstants;
import oracle.jdbc.driver.*;

public class ConnectionManager implements WebConstants
{
  private boolean debug = true;
  protected Connection con;
  protected DebugWriter writer;
  PropertyChangeSupport pcs;
////////////////////////////////////////////////////////////////////////////////
  public ConnectionManager()
  {
    pcs = new PropertyChangeSupport(this);
    writer = new DebugWriter();
  }
////////////////////////////////////////////////////////////////////////////////
  public void setDebug(String b)
  {
    debug = b.equals("true");
  }
////////////////////////////////////////////////////////////////////////////////
  public void addPropertyChangeListener( PropertyChangeListener l)
  {
    pcs.addPropertyChangeListener(l);
  }
////////////////////////////////////////////////////////////////////////////////
  public void removePropertyChangeListener(PropertyChangeListener l)
  {
    pcs.removePropertyChangeListener(l);
  }
////////////////////////////////////////////////////////////////////////////////
  public void login()
  {
    try
    {
      DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
      Class.forName("oracle.jdbc.driver.OracleDriver");
    }
    catch(Exception e)
    {
      if(debug) {  writer.writeDebug("Error setting driver:"+e.getMessage());}
    }
    try
    {
      con = DriverManager.getConnection(url,userId,passWd);
      pcs.firePropertyChange(connection,null,con);
      if(debug)
      {
        writer.writeDebug("connection succeded ! URL:"+url+"User:"+userId+
                          "Pwd:"+passWd);
      }
    }
    catch(Exception e)
    {
      pcs.firePropertyChange(connError,null,e);
      if(debug)
      {