⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 dbaccess.java

📁 一个OR Mapping 工具
💻 JAVA
字号:
package org.dbgen.support;import java.util.*;import java.sql.*;/** * DbAccess is a thin layer API sitting on top of JDBC * Connection/Statement, and is used conveniently to access data * sources by dynamically creating JDBC Statement's as necessary from * a single connection.  When a ResultSet is closed, the Statement * will be re-used in the next query/update operation. * * <p>Example: * * <pre> * String driver = "sun.jdbc.odbc.JdbcOdbcDriver"; * String url    = "jdbc:odbc:datasrc"; * DbAccess dba  = new DbAccess(drv, url, "USER", "PASS"); * ResultSet rs  = dba.executeQuery("select * from tablename"); * while (rs.next()) { *    // do something with the result set. * } * dba.close(rs); // free the Statement for this ResultSet * </pre> */public class DbAccess{  protected Connection conn = null;  protected String driver = null;  protected String url = null;  protected String user = null;  protected String password = null;  private Vector srs = new Vector(2);  boolean fieldDebug = false;  Handler fieldErrorHandler = null;  protected transient java.beans.PropertyChangeSupport propertyChange = new java.beans.PropertyChangeSupport(this);  /**   * Construct a DbAccess object.  The programmer must set the driver,   * url, username, and password properties, and call   * <code>connect()</code> before using other methods in this class.   */  public DbAccess()  {  }  /**   * Construct a DbAccess with the specified JDBC Driver class,   * JDBC url, username and password.   * @exception java.sql.SQLException If database connection failed.   * @exception ClassNotFoundException If the specified driver is not found.   */  public DbAccess(String driver, String url, String user, String password)    throws SQLException, ClassNotFoundException  {    this.driver = driver;    this.url = url;    this.user = user;    this.password = password;    connect(true);  }  /**   * Construct a DbAccess object with the specified JDBC Connection.   */  public DbAccess(Connection conn)  {    this.conn = conn;  }  /**   * The addPropertyChangeListener method was generated to support the propertyChange field.   */  public synchronized void addPropertyChangeListener(java.beans.PropertyChangeListener listener) {    propertyChange.addPropertyChangeListener(listener);  }  /**   * Close the specified ResultSet.  This function MUST BE CALLED so   * that the JDBC Statement can be re-used in subsequent database   * operations.  Failure to do so may exhaust system resources.   * @exception java.sql.SQLException If   * <code>java.sql.ResultSet.close()</code> failed.   */  public void close(ResultSet rs)    throws SQLException  {    for (int i = 0; i < srs.size(); i++) {      SRPair obj = (SRPair) srs.elementAt(i);      if (obj.resultset == rs) {        obj.inuse = false;        //	Util.println("* Free SRPair " + obj);      }    }    rs.close();  }  /**   * Connect to database now.   * @exception java.sql.SQLException If database connection failed.   * @exception ClassNotFoundException If the specified driver is not found.   */  public void connect(boolean reconnect)    throws SQLException, ClassNotFoundException  {    Class.forName(driver);    if (reconnect && conn != null)    {      conn.close();      conn = null;    }    if (conn == null) {      if (user == null || password == null) {        conn = DriverManager.getConnection(url);      } else {        conn = DriverManager.getConnection(url, user, password);      }      //System.out.println("Data Source: " + url + " connected as " + conn);    }  }  /**   * Disconnect from the current JDBC connection.   * @exception java.sql.SQLException When a SQL Exception occurred.   */  public void disconnect()    throws SQLException  {    if (conn != null)    {      conn.close();      conn = null;    }    return;  }  /**   * Execute a SQL statement.  return The ResultSet for this query.   * @exception java.sql.SQLException If <code>java.sql.Statement.executeQuery()</code> failed.   * @return A <code>java.sql.ResultSet</code> object.   */  public ResultSet executeQuery(String query)    throws SQLException  {    try {      if (getConnection() == null) {        connect(true);      }    } catch (ClassNotFoundException exp) {      if (getErrorHandler() != null)      {        getErrorHandler().handle(exp);      }      else      {        exp.printStackTrace(System.err);      }    }    SRPair obj = getSRPair();    if (getDebug())      System.err.println("DbAccess.executeQuery: " + query);    obj.resultset = obj.statement.executeQuery(query);    return obj.resultset;  }  /**   * Execute a SQL Insert/Delete/Update statement.   * @exception java.sql.SQLException If <code>java.sql.Statement.executeUpdate()</code> failed.   * @return The number of rows affected in this update.   */  public int executeUpdate(String sql)    throws SQLException  {    try {      if (getConnection() == null) {        connect(true);      }    } catch (ClassNotFoundException exp) {      if (getErrorHandler() != null)      {        getErrorHandler().handle(exp);      }      else      {        exp.printStackTrace(System.err);      }    }    SRPair obj = getSRPair();    if (getDebug())      System.err.println("DbAccess.executeUpdate: " + sql);    int val = obj.statement.executeUpdate(sql);    obj.inuse = false;    return val;  }  /**   * The firePropertyChange method was generated to support the propertyChange field.   */  public void firePropertyChange(String propertyName, Object oldValue, Object newValue) {    propertyChange.firePropertyChange(propertyName, oldValue, newValue);  }  /**   * Get the connection property.   * @return The JDBC Connection object.   */  public Connection getConnection() {    return conn;  }  /**   * Gets the debug property (boolean) value.   * @return The debug property value.   * @see #setDebug   */  public boolean getDebug() {    /* Returns the debug property value. */    return fieldDebug;  }  /**   * Get the driver property.   * @return The JDBC driver class string.   */  public String getDriver() {    return driver;  }  /**   * Gets the errorHandler property (org.dbgen.support.Handler) value.   * @return The errorHandler property value.   * @see #setErrorHandler   */  public Handler getErrorHandler() {    /* Returns the errorHandler property value. */    return fieldErrorHandler;  }  /**   * Get the password property.   * @return The password for database connection.   */  public String getPassword() {    return password;  }  private synchronized SRPair getSRPair()    throws SQLException  {    SRPair obj;    int len = srs.size();    // search for available statement.    for (int i = 0; i < len; i++) {      obj = (SRPair) srs.elementAt(i);      if (!obj.inuse) {        //System.out.println("* Re-use " + obj);        obj.inuse = true;        return obj;      }    }    // if not, create one and add to vector.    obj = new SRPair(conn.createStatement(), null, true);    //System.out.println("* New SRPair " + obj);    srs.addElement(obj);    // debug    //    Util.println("* Statement count: " + (len+1));    return obj;  }  /**   * Get the url property.   * @return The JDBC url string.   */  public String getUrl() {    return url;  }  /**   * Get the user property.   * @return The username for database connection.   */  public String getUser() {    return user;  }  /**   * Check if the JDBC connection io still available.   * @return True if the connection is still available.   * @exception java.sql.SQLException When a SQL Exception occurred.   */  public boolean isConnected()    throws SQLException  {    /* Test to see if the connection has been closed */    if ((conn != null) && conn.isClosed())      conn = null;    /* If connection existed and it wasn't closed, then it must be good. */    return (conn != null);  }  /**   * The removePropertyChangeListener method was generated to support the propertyChange field.   */  public synchronized void removePropertyChangeListener(java.beans.PropertyChangeListener listener) {    propertyChange.removePropertyChangeListener(listener);  }  /**   * Set the JDBC Connection for this DbAccess object.   * @param conn A JDBC Connection object.   */  public void setConnection(Connection conn) {    this.conn = conn;    //System.out.println("Connection set => " + conn);  }  /**   * Sets the debug property (boolean) value.   * @param debug The new value for the property.   * @see #getDebug   */  public void setDebug(boolean debug) {    fieldDebug = debug;    return;  }  /**   * Set the JDBC driver class string.   * @param driver A JDBC driver class name.   */  public void setDriver(String driver) {    this.driver = driver;  }  /**   * Sets the errorHandler property (org.dbgen.support.Handler) value.   * @param errorHandler The new value for the property.   * @see #getErrorHandler   */  public void setErrorHandler(Handler errorHandler) {    /* Get the old property value for fire property change event. */    Handler oldValue = fieldErrorHandler;    /* Set the errorHandler property (attribute) to the new value. */    fieldErrorHandler = errorHandler;    /* Fire (signal/notify) the errorHandler property change event. */    firePropertyChange("errorHandler", oldValue, errorHandler);    return;  }  /**   * Set the password for database connection.   * @param The password needed to connect to the database.   */  public void setPassword(String password) {    this.password = password;  }  /**   * Set the JDBC url string.   * @param A JDBC URL string.   */  public void setUrl(String url) {    this.url = url;  }  /**   * Set the username for database connection.   * @param The user name needed to connect to the database.   */  public void setUser(String user) {    this.user = user;  }}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -