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

📄 driver.java

📁 一个OR Mapping 工具
💻 JAVA
字号:
package org.dbgen.support;import java.sql.*;import java.util.*;/** * The Driver class is used for all database operations including insertion, * deletion, update, and retrieval of data objects.  An example is available * as follows: * * <PRE> * // Create the driver instance with a DbAccess object. * Driver driver = new Driver(new DbAccess(jdbcDriver, jdbcURL, username, password)); * <P> * // Create a Customer object which was generated from DbGen. * Customer customer = new Customer("666-66-6666"); * <P> * // Now retrieve the customer record. * Customer record = (Customer) driver.retrieve(customer); * <P> * // Try retrieve all customers with first name equals John order by last name. * Vector johns = driver.retrieve(customer, "FirstName = 'John'", "LastName"); * for (int i = 0; i < johns.size(); i++) { *     System.out.println(johns); * } * <P> * // Insert a new customer into the database. * Customer johndoe = new Customer("777-77-7777", "John", "Doe", "213-213-1313"); * driver.insert(johndoe); * <P> * // Update the record we inserted earlier to have new phone number. * johndoe.setPhoneNumber("213-213-0000"); * driver.update(johndoe); * <P> * // Delete John Doe, please? * driver.delete(johndoe); * <P> * // Now see how many customer records are there with first name equals John. * int count = driver.getNumRows(customer, "FirstName = 'John'"); * <P> * // See transactions(detail table rows) for John Doe. * Vector transactions = driver.retrieveDetails(customer, new Transaction()); * </PRE> * */public class Driver {  org.dbgen.support.DbAccess fieldDBA = null;  protected transient java.beans.PropertyChangeSupport propertyChange = new java.beans.PropertyChangeSupport(this);  /**   * Create a new driver instance.  Remember to set the DBA (DbAccess)   * property before using the driver.   */  public Driver() {  }  /**   * Create a new driver instance with the specified DbAccess object.   *   * @param dba A DbAccess object.   */  public Driver(org.dbgen.support.DbAccess dba) {    setDBA(dba);  }  /**   * Java bean property change support.   */  public synchronized void addPropertyChangeListener(java.beans.PropertyChangeListener listener) {    propertyChange.addPropertyChangeListener(listener);  }  /**   * Check the DBA handle.  If not available, just throw a SQLException.   */  private final void checkHandle()    throws SQLException  {    if (getDBA() == null) {      throw new SQLException();    }  }  /**   * Delete the specified data object.   * @return The result value from the JDBC executeUpdate method.   * @param data The data object that needs to be deleted from the database.   * @exception java.sql.SQLException When a SQL Exception occurred during the operation.   */  public int delete(Data data) throws SQLException  {    checkHandle();    String sql = "DELETE FROM " + data.getTableName() + " WHERE " + data.getKeyConditions();    return getDBA().executeUpdate(sql);  }  /**   * Java bean property change support.   */  public void firePropertyChange(String propertyName, Object oldValue, Object newValue) {    propertyChange.firePropertyChange(propertyName, oldValue, newValue);  }  /**   * Get the next batch of records available from the result set.   * An instance of the data is needed in order to create   * the right data objects to return.   *   * @return A vector of records from the result set.   * @param data An instance of the expected data object type.   * @param rs The ResultSet object that was created for the query.   * @param max Maximum number of records to return in this batch.   * @exception java.sql.SQLException When a SQL Exception occurred during the operation.   */  public java.util.Vector getBatchRecords(org.dbgen.support.Data data, ResultSet rs, int max) throws SQLException {    Vector vec = new Vector();    int i;    for (i = 0; i < max; i++)    {      Data obj = getNextRecord(data, rs);      if (data != null)      {        vec.addElement(obj);      }      else      {      break;      }    }    return i > 0 ? vec : null;  }  /**   * Get the next batch of records available from the result set.   * An instance of the data is needed in order to create   * the right data objects to return.   *   * @return An array of records from the result set.   * @param data An instance of the expected data object type.   * @param rs The ResultSet object that was created for the query.   * @param max Maximum number of records to return in this batch.   * @exception java.sql.SQLException When a SQL Exception occurred during the operation.   */  public Data[] getBatchRecordsAsArray(org.dbgen.support.Data data, ResultSet rs, int max) throws SQLException {    return makeDataArrayFromVector(getBatchRecords(data, rs, max));  }  /**   * Gets the DBA property (org.dbgen.support.DbAccess) value.   * @return The DBA property value.   * @see #setDBA   */  public org.dbgen.support.DbAccess getDBA() {    /* Returns the DBA property value. */    if (fieldDBA == null) {      try {        fieldDBA = new org.dbgen.support.DbAccess();      } catch (Throwable exception) {        System.err.println("Exception creating DBA property.");      }    };    return fieldDBA;  }  /**   * Get the next record available from the result set specified by the   * ResultSet ID.  An instance of the data is needed in order to create   * the right data objects to return.   *   * @return The next record from the result set.   * @param data An instance of the expected data object.   * @param rs The ResultSet object that was created for the query.   * @exception java.sql.SQLException When a SQL Exception occurred during the operation.   */  public org.dbgen.support.Data getNextRecord(org.dbgen.support.Data data, ResultSet rs) throws SQLException {    if (rs == null)    {      return null;    }    else    {      if (rs.next())      {        return data.makeObject(rs);      }      getDBA().close(rs);      return null;    }  }  /**   * Get number of rows for this table given a condition.   * @return The number of rows for this table given a condition.   * @param data An instance of the data object for this table.   * @param condition A valid SQL condition string.   * @exception java.sql.SQLException When a SQL Exception occurred during the operation.   * @exception ClassNotFoundException If the JDBC driver cannot be loaded.   */  public int getNumRows(org.dbgen.support.Data data, String condition) throws ClassNotFoundException, SQLException {    checkHandle();    String sql = "SELECT COUNT(*) FROM " + data.getTableName();    if (condition != null && condition.length() > 0) {      sql += " WHERE " + condition;    }    ResultSet rs = getDBA().executeQuery(sql);    rs.next();    int count = rs.getInt(1);    getDBA().close(rs);    return count;  }  /**   * Insert a data object into the database table.   * @return The result value from the JDBC executeUpdate call.   * @param data An instance of the data object that needs to be inserted.   * @exception java.sql.SQLException When a SQL Exception occurred during the operation.   */  public int insert(Data data) throws SQLException  {    checkHandle();    String sql = "INSERT INTO " + data.getTableName() + " VALUES (" + data.getInsertValues() + ")";    return getDBA().executeUpdate(sql);  }  /**   * Return a Data array from a Data vector.   * @param vec java.util.Vector   */  private static Data[] makeDataArrayFromVector(Vector vec) {    Data dataArray[] = new Data[vec.size()];    for (int i = 0; i < vec.size(); i++)    {      dataArray[i] = (Data) vec.elementAt(i);    }    return dataArray;  }  /**   * Execute a SQL query from the specified table. This method returns a   * ResultSet object.  This ResultSet object is then used in the   * getNextRecord(ResultSet rsid) method which retrieves individual record   * from the result set.   *   * @return The corresponding ResultSet from the query.   * @param data An instance of the data object for this table.   * @param condition A valid SQL condition clause.   * @param order A valid SQL order by clause.   * @exception java.sql.SQLException When a SQL Exception occurred during the operation.   */  public ResultSet query(org.dbgen.support.Data data, String condition, String order)    throws SQLException  {    checkHandle();    String sql = "SELECT * FROM " + data.getTableName();    if (condition != null && condition.length() > 0) {      sql += " WHERE " + condition;    }    if (order != null && order.length() > 0) {      sql += " ORDER BY " + order;    }    return getDBA().executeQuery(sql);  }  /**   * Java bean property change support.   */  public synchronized void removePropertyChangeListener(java.beans.PropertyChangeListener listener) {    propertyChange.removePropertyChangeListener(listener);  }  /**   * Retrieve a single record from the table.   * @return An instance of the data object found in the table.   * @param data An instance of data object for this table where the key fields has been set.   * @exception SQLException When a SQL Exception occurred during the operation.   * @exception RecordNotFoundException When the record is not found (incorrect primary key value?)   */  public org.dbgen.support.Data retrieve(org.dbgen.support.Data data) throws SQLException, RecordNotFoundException {    ResultSet rs = query(data, data.getKeyConditions(), null);    org.dbgen.support.Data obj = getNextRecord(data, rs);    if (obj != null)    {      while (getNextRecord(data, rs) != null)        ;    }    else    {      throw new RecordNotFoundException("Cannot find record for data " + data);    }    return obj;  }  /**   * Retrieve a vector of data objects from the table.   * @return A vector of data objects from the table that matches the given condition.   * @param data An instance of data object for this table.   * @param condition A valid SQL WHERE clause.   * @param order A valid SQL ORDER BY clause.   * @exception SQLException When a SQL Exception occurred during the operation.   */  public Vector retrieve(org.dbgen.support.Data data, String condition, String order) throws SQLException {    Vector vec = new Vector();    ResultSet rs = query(data, condition, order);    Object obj;    while ((obj = getNextRecord(data, rs)) != null)    {      vec.addElement(obj);    }    return vec.size() > 0 ? vec : null;  }  /**   * Retrieve an array of data objects from the table.   * @return An array of data objects from the table that matches the given condition.   * @param data An instance of data object for this table.   * @param condition A valid SQL WHERE clause.   * @param order A valid SQL ORDER BY clause.   * @exception SQLException When a SQL Exception occurred during the operation.   */  public org.dbgen.support.Data[] retrieveAsArray(org.dbgen.support.Data data, String condition, String order) throws SQLException {    return makeDataArrayFromVector(retrieve(data, condition, order));  }  /**   * Retrieve child record based on a 1-1 relationship defined in the parent Data class.   *   * @return A vector of data objects that is related to the parent data object.   * @param parent An instance of the parent data object.   * @param child An instance of the child data object.   * @exception SQLException When a SQL Exception occurred during the operation.   * @exception RecordNotFoundException When the record is not found (incorrect primary key value?)   */  public org.dbgen.support.Data retrieveDetail(org.dbgen.support.Data masterData, org.dbgen.support.Data foreignData )    throws SQLException, RecordNotFoundException  {    ResultSet rs = query(foreignData, foreignData.getKeyConditions(masterData), null);    org.dbgen.support.Data obj = getNextRecord(foreignData, rs);    if (obj != null)    {      while (getNextRecord(foreignData, rs) != null)        ;    }    else    {      throw new RecordNotFoundException("Cannot find record for data " + foreignData);    }    return obj;  }  /**   * Retrieve child records based on a 1-n relationship defined in the parent Data class.   *   * @return A vector of data objects that is related to the parent data object.   * @param parent An instance of the parent data object.   * @param child An instance of the child data object.   * @exception SQLException When a SQL Exception occurred during the operation.   * @exception RecordNotFoundException When the record is not found (incorrect primary key value?)   */  public Vector retrieveDetails(org.dbgen.support.Data masterData, org.dbgen.support.Data foreignData)    throws SQLException, RecordNotFoundException  {    Vector vec = new Vector();    ResultSet rs = query(foreignData, foreignData.getKeyConditions(masterData), null);    Object obj;    while ((obj = getNextRecord(foreignData, rs)) != null)    {      vec.addElement(obj);    }    return vec.size() > 0 ? vec : null;  }  /**   * Sets the DBA property (org.dbgen.support.DbAccess) value.   * @param DBA The new value for the property.   * @see #getDBA   */  public void setDBA(org.dbgen.support.DbAccess DBA) {    /* Get the old property value for fire property change event. */    org.dbgen.support.DbAccess oldValue = fieldDBA;    /* Set the DBA property (attribute) to the new value. */    fieldDBA = DBA;    /* Fire (signal/notify) the DBA property change event. */    firePropertyChange("DBA", oldValue, DBA);    return;  }  /**   * Update the data object to the table.   * @return The result value from the JDBC executeUpdate method.   * @param data An instance of data object that needs to be updated.   * @exception java.sql.SQLException When a SQL Exception occurred during the operation.   */  public int update(Data data) throws SQLException  {    checkHandle();    String sql = "UPDATE " + data.getTableName() + " SET " + data.getUpdateValues() + " WHERE " + data.getKeyConditions();    return getDBA().executeUpdate(sql);  }}

⌨️ 快捷键说明

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