Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
   /*
    * $Id: AbstractConnection.java 59380 2014-04-07 14:33:32Z mrotteveel $
    * 
    * Firebird Open Source J2ee connector - jdbc driver
    *
    * Distributable under LGPL license.
    * You may obtain a copy of the License at http://www.gnu.org/copyleft/lgpl.html
    *
    * This program is distributed in the hope that it will be useful,
   * but WITHOUT ANY WARRANTY; without even the implied warranty of
   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   * LGPL License for more details.
   *
   * This file was created by members of the firebird development team.
   * All individual contributions remain the Copyright (C) of those
   * individuals.  Contributors to this file are either listed here or
   * can be obtained from a CVS history command.
   *
   * All rights reserved.
   */
  package org.firebirdsql.jdbc;
  
  import java.sql.Array;
  import java.sql.Blob;
  import java.sql.Clob;
  import java.sql.Struct;
  import java.util.HashMap;
  import java.util.HashSet;
  import java.util.List;
  import java.util.Map;
  import java.util.Set;
  
  
The class AbstractConnection is a handle to a org.firebirdsql.jca.FBManagedConnection.

Author(s):
David Jencks
Version:
1.0
  
  public abstract class AbstractConnection implements FirebirdConnection {
  
      
      // This flag is set tu true in close() method to indicate that this 
      // instance is invalid and cannot be used anymore
      private boolean invalid = false;
  
  
      protected FBManagedConnection mc;
  
      private FBLocalTransaction localTransaction;
      private FBDatabaseMetaData metaData;
      
  
      private SQLWarning firstWarning;
       
      // This set contains all allocated but not closed statements
      // It is used to close them before the connection is closed
      protected HashSet activeStatements = new HashSet();
      
      
      private boolean autoCommit;
      
      private StoredProcedureMetaData storedProcedureMetaData;
 
    
Create a new AbstractConnection instance based on a org.firebirdsql.jca.FBManagedConnection.

Parameters:
mc A FBManagedConnection around which this connection is based
  
      public AbstractConnection(FBManagedConnection mc) {
         this. = mc;
         
         this. = new InternalTransactionCoordinator();
         
         
         else
     }
     
         return ;
     }
     
     public int getHoldability() throws SQLException {
         return this.;
     }
 
     public void setHoldability(int holdabilitythrows SQLException {
         this. = holdability;
     }

    
Check if this connection is valid. This method should be invoked before executing any action in this class.

Throws:
java.sql.SQLException if this connection has been closed and cannot be used anymore.
 
     protected void checkValidity() throws SQLException {
         if ( || isClosed()) {
             throw new FBSQLException(
                 "This connection is closed and cannot be used now.",
                 .);
         }
     }
    
    
This method should be invoked by each of the statements in the java.sql.Statement.close() method. Here we remove statement from the activeStatements set, so we do not need to close it later.

Parameters:
stmt statement that was closed.
 
         if (!.remove(stmt))
             throw new IllegalArgumentException(
                 "Specified statement was not created by this connection.");
     }
    
    
This method closes all active statements and cleans resources.

Throws:
java.sql.SQLException if at least one of the active statements failed to close gracefully.
 
     private void freeStatements() throws SQLException {
         // clone statements to avoid concurrent modification exception
         Set statements = (Set).clone();
         
         // iterate through the set, close statements and collect exceptions
         Iterator iter = statements.iterator();
         SQLExceptionChainBuilder chain = new SQLExceptionChainBuilder();
         while(iter.hasNext()) {
             try {
                 AbstractStatement stmt = (AbstractStatement)iter.next();
                 stmt.close();
             } catch(SQLException ex) {
                 chain.append(ex);
             }
         }
         
         // throw exception if there is any
         if (chain.hasException()) throw chain.getException();
     }

    
Set the org.firebirdsql.jca.FBManagedConnection around which this connection is based.

Parameters:
mc The FBManagedConnection around which this connection is based
 
     public void setManagedConnection(FBManagedConnection mc) {
         //close any prepared statements we may have executed.
         if (this. != mc &&  != null) {
             .close();
              = null;
         }
         this. = mc;
     }
     
         return ;
     }

    
Get connection handle for direct Firebird API access

Returns:
internal handle for connection
Throws:
org.firebirdsql.gds.GDSException if handle needed to be created and creation failed
 
     public IscDbHandle getIscDBHandle() throws GDSException {
         return getGDSHelper().getIscDBHandle();
     }

    
Get Firebird API handler (sockets/native/embeded/etc)

Returns:
handler object for internal API calls
 
     public GDS getInternalAPIHandler() throws SQLException {
         try {
             return getGDSHelper().getInternalAPIHandler();
         } catch(GDSException ex) {
             throw new FBSQLException(ex);
         }
     }
    
    
Get database parameter buffer for this connection.

 
         return .getConnectionRequestInfo().getDpb();
     }
 
     
 	public void setTransactionParameters(int isolationLevelint[] parameters)
 		throws SQLException {
         
         
         for (int i = 0; i < parameters.lengthi++) {
 			tpbParams.addArgument(parameters[i]);
 		}
         
         setTransactionParameters(isolationLeveltpbParams);
 	}
     
     public TransactionParameterBuffer getTransactionParameters(int isolationLevelthrows SQLException {
         return .getTransactionParameters(isolationLevel);
     }
 
     }
     
     public void setTransactionParameters(int isolationLevelTransactionParameterBuffer tpbthrows SQLException {
         if (.isManagedEnvironment())
             throw new FBSQLException("Cannot set transaction parameters " +
                     "in managed environment.");
         
         .setTransactionParameters(isolationLeveltpb);
     }
     
     public void setTransactionParameters(TransactionParameterBuffer tpbthrows SQLException {
         try {
             if (getLocalTransaction().inTransaction())
                 throw new FBSQLException("Cannot set transaction parameters " +
                         "when transaction is already started.");
             
             .setTransactionParameters(tpb);
         } catch(ResourceException ex) {
             throw new FBSQLException(ex);
         }
     }

    
Creates a Statement object for sending SQL statements to the database. SQL statements without parameters are normally executed using Statement objects. If the same SQL statement is executed many times, it is more efficient to use a PreparedStatement object.

Result sets created using the returned Statement object will by default have forward-only type and read-only concurrency.

Returns:
a new Statement object
Throws:
java.sql.SQLException if a database access error occurs
 
     public synchronized Statement createStatement() throws SQLException {
         return createStatement(
             .
             .,
             
         );
     }


    
Creates a PreparedStatement object for sending parameterized SQL statements to the database. A SQL statement with or without IN parameters can be pre-compiled and stored in a PreparedStatement object. This object can then be used to efficiently execute this statement multiple times.

Note: This method is optimized for handling parametric SQL statements that benefit from precompilation. If the driver supports precompilation, the method prepareStatement will send the statement to the database for precompilation. Some drivers may not support precompilation. In this case, the statement may not be sent to the database until the PreparedStatement is executed. This has no direct effect on users; however, it does affect which method throws certain SQLExceptions. Result sets created using the returned PreparedStatement will have forward-only type and read-only concurrency, by default.

Parameters:
sql a SQL statement that may contain one or more '?' IN parameter placeholders
Returns:
a new PreparedStatement object containing the pre-compiled statement
Throws:
java.sql.SQLException if a database access error occurs
 
     public synchronized PreparedStatement prepareStatement(String sql)
     throws SQLException {
     }

    
Creates a CallableStatement object for calling database stored procedures. The CallableStatement object provides methods for setting up its IN and OUT parameters, and methods for executing the call to a stored procedure.

Note: This method is optimized for handling stored procedure call statements. Some drivers may send the call statement to the database when the method prepareCall is done; others may wait until the CallableStatement object is executed. This has no direct effect on users; however, it does affect which method throws certain SQLExceptions. Result sets created using the returned CallableStatement will have forward-only type and read-only concurrency, by default.

Parameters:
sql a SQL statement that may contain one or more '?' parameter placeholders. Typically this statement is a JDBC function call escape string.
Returns:
a new CallableStatement object containing the pre-compiled SQL statement
Throws:
java.sql.SQLException if a database access error occurs
 
     public synchronized CallableStatement prepareCall(String sql
     throws SQLException {
         return prepareCall(sql
                 ..);
     }
     
     public synchronized Blob createBlob() throws SQLException {
         try {
             return new FBBlob(getGDSHelper(), );
         } catch(GDSException ex) {
             throw new FBSQLException(ex);
         }
     }
     
     public Clob createClob() throws SQLException {
         FBBlob blob = (FBBlob)createBlob();
         return new FBClob(blob);
     }
     
     public Struct createStruct(String typeNameObject[] attributes)
             throws SQLException {
         throw new FBDriverNotCapableException();
     }
     
     public Array createArrayOf(String typeNameObject[] elements)
             throws SQLException {
         throw new FBDriverNotCapableException();
     }

    
Converts the given SQL statement into the system's native SQL grammar. A driver may convert the JDBC sql grammar into its system's native SQL grammar prior to sending it; this method returns the native form of the statement that the driver would have sent.

Parameters:
sql a SQL statement that may contain one or more '?' parameter placeholders
Returns:
the native form of this statement
Throws:
java.sql.SQLException if a database access error occurs
 
     public synchronized String nativeSQL(String sqlthrows SQLException {
         
         
         int mode = .;
         
             mode = .;
         
         return new FBEscapedParser(mode).parse(sql);
     }

    
Sets this connection's auto-commit mode. If a connection is in auto-commit mode, then all its SQL statements will be executed and committed as individual transactions. Otherwise, its SQL statements are grouped into transactions that are terminated by a call to either the method commit or the method rollback. By default, new connections are in auto-commit mode. The commit occurs when the statement completes or the next execute occurs, whichever comes first. In the case of statements returning a ResultSet, the statement completes when the last row of the ResultSet has been retrieved or the ResultSet has been closed. In advanced cases, a single statement may return multiple results as well as output parameter values. In these cases the commit occurs when all results and output parameter values have been retrieved.

Parameters:
autoCommit true enables auto-commit; false disables auto-commit.
Throws:
java.sql.SQLException if a database access error occurs
 
     public synchronized void setAutoCommit(boolean autoCommitthrows SQLException {
         checkValidity();
         
         if (this. == autoCommit
             return;
         
         if (autoCommit && .inDistributedTransaction()) {
             throw new FBSQLException("Connection enlisted in distributed transaction".);
         }
         
         if (autoCommit)
             coordinator = new InternalTransactionCoordinator.AutoCommitCoordinator(thisgetLocalTransaction());
         else
             coordinator = new InternalTransactionCoordinator.LocalTransactionCoordinator(thisgetLocalTransaction());
         
         .setCoordinator(coordinator);
         this. = autoCommit;
     }
 
     public synchronized void setManagedEnvironment(boolean managedConnectionthrows SQLException {
         checkValidity();
         
         if (managedConnection && .inDistributedTransaction()) {
             coordinator = new InternalTransactionCoordinator.ManagedTransactionCoordinator(this);
             this. = false;
         } else {
             coordinator = new InternalTransactionCoordinator.AutoCommitCoordinator(thisgetLocalTransaction());
             this. = true;
         }
          
         .setCoordinator(coordinator);
     }

    
Gets the current auto-commit state.

Returns:
the current state of auto-commit mode
Throws:
java.sql.SQLException if a database access error occurs
See also:
setAutoCommit(boolean)
 
     public synchronized boolean getAutoCommit() throws SQLException {
         if (isClosed())
             throw new FBSQLException("You cannot getAutomcommit on an " +
                     "unassociated closed connection.");
 
         return this.;
     }


    
Makes all changes made since the previous commit/rollback permanent and releases any database locks currently held by the Connection. This method should be used only when auto-commit mode has been disabled.

Throws:
java.sql.SQLException if a database access error occurs
See also:
setAutoCommit(boolean)
 
     public synchronized void commit() throws SQLException {
         if (isClosed()) {
             throw new FBSQLException(
                 "You cannot commit a closed connection.",
                 .);
         }
         
         if (.inDistributedTransaction()) {
             throw new FBSQLException("Connection enlisted in distributed transaction".);
         }
 
         .commit();
     }


    
Drops all changes made since the previous commit/rollback and releases any database locks currently held by this Connection. This method should be used only when auto- commit has been disabled.

Throws:
java.sql.SQLException if a database access error occurs
See also:
setAutoCommit(boolean)
 
     public synchronized void rollback() throws SQLException {
         if (isClosed()) {
             throw new FBSQLException(
                 "You cannot rollback closed connection.",
                 .);
         }
         
         if (.inDistributedTransaction()) {
             throw new FBSQLException("Connection enlisted in distributed transaction".);
         }
 
         .rollback();
     }
    
    
Invalidate everything that should only last for the lifetime of the current transaction.
 
     protected void invalidateTransactionLifetimeObjects(){
     	 = null;
     }

    
Releases a Connection's database and JDBC resources immediately instead of waiting for them to be automatically released.

Note: A Connection is automatically closed when it is garbage collected. Certain fatal errors also result in a closed Connection.

Throws:
java.sql.SQLException if a database access error occurs
 
     public synchronized void close() throws SQLException {
         try {
             try {
                 freeStatements();
             } finally {
 
                 if ( != null) {
                     // if we are in a transaction started
                     // automatically because autocommit = false, roll it back.
 
                     // leave managed transactions alone, they are normally
                     // committed after the Connection handle is closed.
 
                     if (!getAutoCommit() && getLocalTransaction().inTransaction()) {
                         // autocommit is always true for managed tx.
                         try {
                             .rollback();
                         } finally {
                             setAutoCommit(true);
                         }
                     }
 
                     .close(this);
                      = null;
                 }
             }
         } catch (ResourceException ex) {
             throw new FBSQLException(ex);
         }
     }


    
Tests to see if a Connection is closed.

Returns:
true if the connection is closed; false if it's still open
 
     public boolean isClosed() {
         return  == null;
     }
     
     public boolean isValid(int timeoutthrows SQLException {
         try {
             GDS gds = getInternalAPIHandler();
             
             byte[] infoRequest = new byte[] {..};
             gds.iscDatabaseInfo(getIscDBHandle(), infoRequest, 1024);
             return true;
         } catch(GDSException ex) {
             return false;
         }
     }
 
     //======================================================================
     // Advanced features:
 
    
Gets the metadata regarding this connection's database. A Connection's database is able to provide information describing its tables, its supported SQL grammar, its stored procedures, the capabilities of this connection, and so on. This information is made available through a DatabaseMetaData object.

Returns:
a DatabaseMetaData object for this Connection
Throws:
java.sql.SQLException if a database access error occurs
 
     public synchronized DatabaseMetaData getMetaData() throws SQLException {
         try {
             if ( == null
                  = new FBDatabaseMetaData(this);
             
             
             return ;
         } catch(GDSException ex) {
             throw new FBSQLException(ex);
         }
     }


    
Puts this connection in read-only mode as a hint to enable database optimizations.

Note: This method cannot be called while in the middle of a transaction.

Parameters:
readOnly true enables read-only mode; false disables read-only mode.
Throws:
java.sql.SQLException if a database access error occurs
 
     public synchronized void setReadOnly(boolean readOnlythrows SQLException {
         try {
             if (getLocalTransaction().inTransaction() && !.isManagedEnvironment())
                 throw new FBSQLException("Calling setReadOnly(boolean) method " +
                         "is not allowed when transaction is already started.");
             
             .setReadOnly(readOnly);
         } catch(ResourceException ex) {
             throw new FBSQLException(ex);
         }
     }


    
Tests to see if the connection is in read-only mode.

Returns:
true if connection is read-only and false otherwise
Throws:
java.sql.SQLException if a database access error occurs
 
     public boolean isReadOnly() throws SQLException {
         return .isReadOnly();
     }


    
Sets a catalog name in order to select a subspace of this Connection's database in which to work. If the driver does not support catalogs, it will silently ignore this request.

Throws:
java.sql.SQLException if a database access error occurs
 
     public void setCatalog(String catalogthrows SQLException {
         checkValidity();
     }


    
Returns the Connection's current catalog name.

Returns:
the current catalog name or null
Throws:
java.sql.SQLException if a database access error occurs
 
     public String getCatalog() throws SQLException {
         checkValidity();
         return null;
     }



    
Attempts to change the transaction isolation level to the one given. The constants defined in the interface Connection are the possible transaction isolation levels.

Calling this method will commit any current transaction.

Parameters:
level one of the TRANSACTION_* isolation values with the exception of TRANSACTION_NONE; some databases may not support other values
Throws:
java.sql.SQLException if a database access error occurs
See also:
java.sql.DatabaseMetaData.supportsTransactionIsolationLevel(int)
 
     public synchronized void setTransactionIsolation(int level
         throws SQLException 
     {
         if (isClosed())
             throw new FBSQLException(
                     "Connection has being closed.",
                     .);
         
         try {
 
             if (!getAutoCommit() && !.isManagedEnvironment())
                 .commit();
 
             .setTransactionIsolation(level);
 
         } catch (ResourceException re) {
             throw new FBSQLException(re);
         } 
     }

    
Gets this Connection's current transaction isolation level.

Returns:
the current TRANSACTION_* mode value
Throws:
java.sql.SQLException if a database access error occurs
 
     public synchronized int getTransactionIsolation() throws SQLException {
         try 
         {
             return .getTransactionIsolation();
         }
         catch (ResourceException e)
         {
             throw new FBSQLException(e);
         } // end of try-catch
     }


    
Returns the first warning reported by calls on this Connection.

Note: Subsequent warnings will be chained to this SQLWarning.

Returns:
the first SQLWarning or null
Throws:
java.sql.SQLException if a database access error occurs
 
     public synchronized SQLWarning getWarnings() throws SQLException {
         SQLWarning warning = ;
         SQLWarning iscWarning = getIscWarnings();
         
         if (warning == null)
             warning = iscWarning;
         else
         if (iscWarning != null)
             warning.setNextWarning(iscWarning);
             
         return warning;
     }


    
Clears all warnings reported for this Connection object. After a call to this method, the method getWarnings returns null until a new warning is reported for this Connection.

Throws:
java.sql.SQLException if a database access error occurs
 
     public synchronized void clearWarnings() throws SQLException {
 		  = null;
          clearIscWarnings();
     }

    
Creates a Statement object that will generate ResultSet objects with the given type and concurrency. This method is the same as the createStatement method above, but it allows the default result set type and result set concurrency type to be overridden.

Parameters:
resultSetType a result set type; see ResultSet.TYPE_XXX
resultSetConcurrency a concurrency type; see ResultSet.CONCUR_XXX
Returns:
a new Statement object
Throws:
java.sql.SQLException if a database access error occurs
Since:
1.2
See also:
What Is in the JDBC 2.0 API
 
     
     public synchronized Statement createStatement(int resultSetType
             int resultSetConcurrencythrows SQLException {
         return createStatement(resultSetTyperesultSetConcurrencythis.);
     }
    
    
Creates a Statement object that will generate ResultSet objects with the given type, concurrency, and holdability. This method is the same as the createStatement method above, but it allows the default result set type, concurrency, and holdability to be overridden.

Parameters:
resultSetType one of the following ResultSet constants: ResultSet.TYPE_FORWARD_ONLY, ResultSet.TYPE_SCROLL_INSENSITIVE, or ResultSet.TYPE_SCROLL_SENSITIVE
resultSetConcurrency one of the following ResultSet constants: ResultSet.CONCUR_READ_ONLY or ResultSet.CONCUR_UPDATABLE
resultSetHoldability one of the following ResultSet constants: ResultSet.HOLD_CURSORS_OVER_COMMIT or ResultSet.CLOSE_CURSORS_AT_COMMIT
Returns:
a new Statement object that will generate ResultSet objects with the given type, concurrency, and holdability
Throws:
java.sql.SQLException if a database access error occurs or the given parameters are not ResultSet constants indicating type, concurrency, and holdability
Since:
1.4
See also:
java.sql.ResultSet
 
     public synchronized Statement createStatement(int resultSetType
         int resultSetConcurrencyint resultSetHoldabilitythrows SQLException 
     {
         if (resultSetHoldability == . && 
                 resultSetType == .) {
 
             addWarning(new FBSQLWarning("Holdable result set must be scrollable."));
             resultSetType = .;
         }
         
         if (resultSetType == .) {
             addWarning(new FBSQLWarning("Unsupported type and/or concurrency"));
             resultSetType = .;
         }			  
           
         checkHoldability(resultSetTyperesultSetHoldability);
         
         try {
             Statement stmt = FBStatementFactory.createStatement(getGDSHelper(), resultSetType,
                     resultSetConcurrencyresultSetHoldability);
             
             .add(stmt);
             return stmt;
         } catch(GDSException ex) {
             throw new FBSQLException(ex);
         }
     }

    
Check whether result set type and holdability are compatible.

Parameters:
resultSetType desired result set type.
resultSetHoldability desired result set holdability.
Throws:
java.sql.SQLException if specified result set type and holdability are not compatibe.
 
     private void checkHoldability(int resultSetTypeint resultSetHoldabilitythrows SQLException {
         boolean holdable = 
             resultSetHoldability == .;
         
         boolean notScrollable = resultSetType != .;
 
         if (holdable && notScrollable
             throw new FBDriverNotCapableException(
                     "Holdable cursors are supported only " +
                     "for scrollable insensitive result sets.");
     }


    
Creates a PreparedStatement object that will generate ResultSet objects with the given type and concurrency. This method is the same as the prepareStatement method above, but it allows the default result set type and result set concurrency type to be overridden.

Parameters:
resultSetType a result set type; see ResultSet.TYPE_XXX
resultSetConcurrency a concurrency type; see ResultSet.CONCUR_XXX
Returns:
a new PreparedStatement object containing the pre-compiled SQL statement
Throws:
java.sql.SQLException if a database access error occurs
Since:
1.2
See also:
What Is in the JDBC 2.0 API
 
     public synchronized PreparedStatement prepareStatement(String sql
             int resultSetTypeint resultSetConcurrencythrows SQLException {
         return prepareStatement(sqlresultSetTyperesultSetConcurrencythis.);
     }

    
Creates a PreparedStatement object that will generate ResultSet objects with the given type, concurrency, and holdability.

This method is the same as the prepareStatement method above, but it allows the default result set type, concurrency, and holdability to be overridden.

Parameters:
sql a String object that is the SQL statement to be sent to the database; may contain one or more '?' IN parameters
resultSetType one of the following ResultSet constants: ResultSet.TYPE_FORWARD_ONLY, ResultSet.TYPE_SCROLL_INSENSITIVE, or ResultSet.TYPE_SCROLL_SENSITIVE
resultSetConcurrency one of the following ResultSet constants: ResultSet.CONCUR_READ_ONLY or ResultSet.CONCUR_UPDATABLE
resultSetHoldability one of the following ResultSet constants: ResultSet.HOLD_CURSORS_OVER_COMMIT or ResultSet.CLOSE_CURSORS_AT_COMMIT
Returns:
a new PreparedStatement object, containing the pre-compiled SQL statement, that will generate ResultSet objects with the given type, concurrency, and holdability
Throws:
java.sql.SQLException if a database access error occurs, this method is called on a closed connection or the given parameters are not ResultSet constants indicating type, concurrency, and holdability
java.sql.SQLFeatureNotSupportedException if the JDBC driver does not support this method or this method is not supported for the specified result set type, result set holdability and result set concurrency.
Since:
1.4
See also:
java.sql.ResultSet
 
     public synchronized PreparedStatement prepareStatement(String sql,
             int resultSetTypeint resultSetConcurrency,
             int resultSetHoldabilitythrows SQLException {
         
         return prepareStatement(sqlresultSetTyperesultSetConcurrency,
             resultSetHoldabilityfalsefalse);
     }
     
     protected synchronized PreparedStatement prepareMetaDataStatement(String sql,
             int resultSetTypeint resultSetConcurrencythrows SQLException {
         
         return prepareStatement(sqlresultSetTyperesultSetConcurrency,
             truefalse);
     }
    
    
Creates a default PreparedStatement object that has the capability to retrieve auto-generated keys. The given constant tells the driver whether it should make auto-generated keys available for retrieval. This parameter is ignored if the SQL statement is not an INSERT statement, or an SQL statement able to return auto-generated keys (the list of such statements is vendor-specific).

Note: This method is optimized for handling parametric SQL statements that benefit from precompilation. If the driver supports precompilation, the method prepareStatement will send the statement to the database for precompilation. Some drivers may not support precompilation. In this case, the statement may not be sent to the database until the PreparedStatement object is executed. This has no direct effect on users; however, it does affect which methods throw certain SQLExceptions.

Result sets created using the returned PreparedStatement object will by default be type TYPE_FORWARD_ONLY and have a concurrency level of CONCUR_READ_ONLY. The holdability of the created result sets can be determined by calling getHoldability().

Parameters:
sql an SQL statement that may contain one or more '?' IN parameter placeholders
autoGeneratedKeys a flag indicating whether auto-generated keys should be returned; one of Statement.RETURN_GENERATED_KEYS or Statement.NO_GENERATED_KEYS
Returns:
a new PreparedStatement object, containing the pre-compiled SQL statement, that will have the capability of returning auto-generated keys
Throws:
java.sql.SQLException if a database access error occurs, this method is called on a closed connection or the given parameter is not a Statement constant indicating whether auto-generated keys should be returned
java.sql.SQLFeatureNotSupportedException if the JDBC driver does not support this method with a constant of Statement.RETURN_GENERATED_KEYS
Since:
1.4
 
     public PreparedStatement prepareStatement(String sqlint autoGeneratedKeys)
             throws SQLException {
     	
     	checkValidity();
         if (autoGeneratedKeys == .) {
            checkAutoGeneratedKeysSupport();
        }
        
        GeneratedKeysQuery query = new GeneratedKeysQuery(sqlautoGeneratedKeys);
        return prepareStatement(query);
    }

    
Creates a default PreparedStatement object capable of returning the auto-generated keys designated by the given array. This array contains the indexes of the columns in the target table that contain the auto-generated keys that should be made available. The driver will ignore the array if the SQL statement is not an INSERT statement, or an SQL statement able to return auto-generated keys (the list of such statements is vendor-specific).

An SQL statement with or without IN parameters can be pre-compiled and stored in a PreparedStatement object. This object can then be used to efficiently execute this statement multiple times.

Note: This method is optimized for handling parametric SQL statements that benefit from precompilation. If the driver supports precompilation, the method prepareStatement will send the statement to the database for precompilation. Some drivers may not support precompilation. In this case, the statement may not be sent to the database until the PreparedStatement object is executed. This has no direct effect on users; however, it does affect which methods throw certain SQLExceptions.

Result sets created using the returned PreparedStatement object will by default be type TYPE_FORWARD_ONLY and have a concurrency level of CONCUR_READ_ONLY. The holdability of the created result sets can be determined by calling getHoldability().

Parameters:
sql an SQL statement that may contain one or more '?' IN parameter placeholders
columnIndexes an array of column indexes indicating the columns that should be returned from the inserted row or rows
Returns:
a new PreparedStatement object, containing the pre-compiled statement, that is capable of returning the auto-generated keys designated by the given array of column indexes
Throws:
java.sql.SQLException if a database access error occurs or this method is called on a closed connection
java.sql.SQLFeatureNotSupportedException if the JDBC driver does not support this method
Since:
1.4
    public PreparedStatement prepareStatement(String sqlint[] columnIndexes)
            throws SQLException {
    	checkValidity();
        GeneratedKeysQuery query = new GeneratedKeysQuery(sqlcolumnIndexes);
        return prepareStatement(query);
    }

    
Creates a default PreparedStatement object capable of returning the auto-generated keys designated by the given array. This array contains the names of the columns in the target table that contain the auto-generated keys that should be returned. The driver will ignore the array if the SQL statement is not an INSERT statement, or an SQL statement able to return auto-generated keys (the list of such statements is vendor-specific).

An SQL statement with or without IN parameters can be pre-compiled and stored in a PreparedStatement object. This object can then be used to efficiently execute this statement multiple times.

Note: This method is optimized for handling parametric SQL statements that benefit from precompilation. If the driver supports precompilation, the method prepareStatement will send the statement to the database for precompilation. Some drivers may not support precompilation. In this case, the statement may not be sent to the database until the PreparedStatement object is executed. This has no direct effect on users; however, it does affect which methods throw certain SQLExceptions.

Result sets created using the returned PreparedStatement object will by default be type TYPE_FORWARD_ONLY and have a concurrency level of CONCUR_READ_ONLY. The holdability of the created result sets can be determined by calling getHoldability().

Parameters:
sql an SQL statement that may contain one or more '?' IN parameter placeholders
columnNames an array of column names indicating the columns that should be returned from the inserted row or rows
Returns:
a new PreparedStatement object, containing the pre-compiled statement, that is capable of returning the auto-generated keys designated by the given array of column names
Throws:
java.sql.SQLException if a database access error occurs or this method is called on a closed connection
java.sql.SQLFeatureNotSupportedException if the JDBC driver does not support this method
Since:
1.4
    public PreparedStatement prepareStatement(String sqlString[] columnNames)
            throws SQLException {
        checkValidity();
        GeneratedKeysQuery query = new GeneratedKeysQuery(sqlcolumnNames);
        return prepareStatement(query);
    }
    
    
Prepares a statement for generated keys.

Parameters:
query AbstractGeneratedKeysQuery instance
Returns:
PreparedStatement object
Throws:
java.sql.SQLException if a database access error occurs or this method is called on a closed connection
        if (query.generatesKeys()) {
            return prepareStatement(query.getQueryString(), 
                    .
                    .
                    .
                    falsetrue);
        } else {
            return prepareStatement(query.getQueryString());
        }
    }
    
    
Helper method to check support of autoGeneratedKeys

Throws:
java.sql.SQLException If the feature is not supported, or if an error occurred retrieving the server version.
    protected void checkAutoGeneratedKeysSupport() throws SQLException {
        GDSHelper gdsHelper;
        try {
            gdsHelper = getGDSHelper();
        } catch (GDSException ex) {
            throw new FBSQLException(ex);
        }
        if (gdsHelper.compareToVersion(2, 0) < 0) {
            throw new FBDriverNotCapableException("This version of Firebird does not support retrieving generated keys (support was added in Firebird 2.0)");
        }
    }
    
    protected synchronized PreparedStatement prepareStatement(String sql
        int resultSetTypeint resultSetConcurrencyint resultSetHoldability
        boolean metaDataboolean generatedKeysthrows SQLException 
    {
          PreparedStatement stmt;
          
          if (resultSetHoldability == . && 
                  resultSetType == .) {
              addWarning(new FBSQLWarning("Holdable result set must be scrollable."));
              resultSetType = .;
          }
		  if (resultSetType == .)
		  {
		      addWarning(new FBSQLWarning("resultSetType or resultSetConcurrency changed"));
              
              if (resultSetType == .)
                  resultSetType = .;
              
		  }
          
          checkHoldability(resultSetTyperesultSetHoldability);
          
          try {
              FBObjectListener.StatementListener coordinator = ;
              if (metaData
                  coordinator = new InternalTransactionCoordinator.MetaDataTransactionCoordinator();
              FBObjectListener.BlobListener blobCoordinator;
              if (metaData)
                  blobCoordinator = null;
              else
                  blobCoordinator = ;
              
              stmt = FBStatementFactory.createPreparedStatement(
                      getGDSHelper(), sqlresultSetTyperesultSetConcurrency
                      resultSetHoldabilitycoordinatorblobCoordinator
                      metaDatafalsegeneratedKeys);
              
              .add(stmt);
              return stmt;
              
          } catch(GDSException ex) {
              throw new FBSQLException(ex);
          }
    }

    
Creates a CallableStatement object that will generate ResultSet objects with the given type and concurrency. This method is the same as the prepareCall method above, but it allows the default result set type and result set concurrency type to be overridden.

Parameters:
resultSetType a result set type; see ResultSet.TYPE_XXX
resultSetConcurrency a concurrency type; see ResultSet.CONCUR_XXX
Returns:
a new CallableStatement object containing the pre-compiled SQL statement
Throws:
java.sql.SQLException if a database access error occurs
Since:
1.2
See also:
What Is in the JDBC 2.0 API
    public synchronized CallableStatement prepareCall(String sql
            int resultSetTypeint resultSetConcurrencythrows SQLException {
        return prepareCall(sqlresultSetTyperesultSetConcurrencythis.);
    }
            
    public synchronized CallableStatement prepareCall(String sql
        int resultSetTypeint resultSetConcurrencyint resultSetHoldabilitythrows SQLException 
    {
        AbstractCallableStatement stmt;
        
        if (resultSetHoldability == . && 
                resultSetType == .) {
            addWarning(new FBSQLWarning("Holdable result set must be scrollable."));
            resultSetType = .;
        }
        
		if (resultSetType == .)
            addWarning(new FBSQLWarning("Scroll-sensitive result sets are not supported."));
            resultSetType = .;
        }
        
        if (resultSetConcurrency != .) {
            addWarning(new FBSQLWarning(
                "Updatable result sets from stored procedures are not supported."));
            resultSetConcurrency = .;
        }	
        checkHoldability(resultSetTyperesultSetHoldability);
        if ( == null){
        	 = StoredProcedureMetaDataFactory.getInstance(this);
        }
        
        try {
            stmt = FBStatementFactory.createCallableStatement(getGDSHelper(), sqlresultSetType,
                    resultSetConcurrencyresultSetHoldability);
            .add(stmt);
            
            return stmt;
        } catch(GDSException ex) {
            throw new FBSQLException(ex);
        }
    }


    
Gets the type map object associated with this connection. Unless the application has added an entry to the type map, the map returned will be empty.

Returns:
the java.util.Map object associated with this Connection object
Since:
1.2
See also:
What Is in the JDBC 2.0 API
    public Map getTypeMap() throws SQLException {
    	return new HashMap();
    }


    
Installs the given type map as the type map for this connection. The type map will be used for the custom mapping of SQL structured types and distinct types.

Parameters:
map the java.util.Map object to install as the replacement for this Connection object's default type map
Since:
1.2
See also:
What Is in the JDBC 2.0 API
    public void setTypeMap(Map mapthrows SQLException {
        throw new FBDriverNotCapableException();
    }
    
    
    /*
     * Savepoint stuff.  
     */
    
    public Savepoint setSavepoint() throws SQLException {
        return (Savepoint)setFirebirdSavepoint();
    }
    public Savepoint setSavepoint(String namethrows SQLException {
        return (Savepoint)setFirebirdSavepoint(name);
    }
    @SuppressWarnings("deprecation")
    public void rollback(Savepoint savepointthrows SQLException {
        rollback((FirebirdSavepoint)savepoint);
    }
    @SuppressWarnings("deprecation")
    public void releaseSavepoint(Savepoint savepointthrows SQLException {
        releaseSavepoint((FirebirdSavepoint)savepoint);
    }
    
    private int savepointCounter = 0;
    private List savepoints = new LinkedList();
    private synchronized int getNextSavepointCounter() {
        return ++;
    }
    
    
Creates an unnamed savepoint in the current transaction and returns the new Savepoint object that represents it.

Deprecated:
This method will be removed in Jaybird 2.3, use java.sql.Connection.setSavepoint()
Returns:
the new Savepoint object
Throws:
java.sql.SQLException if a database access error occurs or this Connection object is currently in auto-commit mode
See also:
java.sql.Savepoint
    public synchronized FirebirdSavepoint setFirebirdSavepoint() throws SQLException {
        FBSavepoint savepoint = new FBSavepoint(getNextSavepointCounter());
        setSavepoint(savepoint);
        
        return savepoint;
    }
    
    
Set the savepoint on the server.

Parameters:
savepoint savepoint to set.
Throws:
java.sql.SQLException if something went wrong.
    private void setSavepoint(FBSavepoint savepointthrows SQLException {
        if (getAutoCommit()) {
            throw new SQLException("Connection.setSavepoint() method cannot " + 
                    "be used in auto-commit mode.".);
        }
        
        if (.inDistributedTransaction()) {
            throw new FBSQLException("Connection enlisted in distributed transaction".);
        }
        try {
            .ensureTransaction();
            
            getGDSHelper().executeImmediate("SAVEPOINT " + savepoint.getServerSavepointId());
            .add(savepoint);
        } catch(GDSException ex) {
            throw new FBSQLException(ex);
        }
    }

    
Creates a savepoint with the given name in the current transaction and returns the new Savepoint object that represents it.

Deprecated:
This method will be removed in Jaybird 2.3, use java.sql.Connection.setSavepoint()
Parameters:
name a String containing the name of the savepoint
Returns:
the new Savepoint object
Throws:
java.sql.SQLException if a database access error occurs or this Connection object is currently in auto-commit mode
See also:
java.sql.Savepoint
    public synchronized FirebirdSavepoint setFirebirdSavepoint(String namethrows SQLException {
        FBSavepoint savepoint = new FBSavepoint(name);
        setSavepoint(savepoint);
        
        return savepoint;
    }
    
    
Undoes all changes made after the given Savepoint object was set.

This method should be used only when auto-commit has been disabled.

Deprecated:
This method will be removed in Jaybird 2.3, use java.sql.Connection.rollback(java.sql.Savepoint)
Parameters:
savepoint the Savepoint object to roll back to
Throws:
java.sql.SQLException if a database access error occurs, the Savepoint object is no longer valid, or this Connection object is currently in auto-commit mode
See also:
java.sql.Savepoint
rollback()
    public synchronized void rollback(FirebirdSavepoint savepointthrows SQLException {
        
        if (getAutoCommit())
            throw new SQLException("Connection.setSavepoint() method cannot " + 
                    "be used in auto-commit mode.");
        
        if (!(savepoint instanceof FBSavepoint))
            throw new SQLException(
                    "Specified savepoint was not obtained from this connection.");
        
        if (.inDistributedTransaction()) {
            throw new FBSQLException("Connection enlisted in distributed transaction".);
        }
        
        FBSavepoint fbSavepoint = (FBSavepoint)savepoint;
        
        if (!fbSavepoint.isValid())
            throw new SQLException("Savepoint is no longer valid.");
        
        try {
            getGDSHelper().executeImmediate(
                    "ROLLBACK TO " + fbSavepoint.getServerSavepointId());
        } catch (GDSException ex) {
            throw new FBSQLException(ex);
        }
    }

    
Removes the given Savepoint object from the current transaction. Any reference to the savepoint after it have been removed will cause an SQLException to be thrown.

Deprecated:
This method will be removed in Jaybird 2.3, use java.sql.Connection.releaseSavepoint(java.sql.Savepoint)
Parameters:
savepoint the Savepoint object to be removed
Throws:
java.sql.SQLException if a database access error occurs or the given Savepoint object is not a valid savepoint in the current transaction
    public synchronized void releaseSavepoint(FirebirdSavepoint savepointthrows SQLException {
        
        if (getAutoCommit())
            throw new SQLException("Connection.setSavepoint() method cannot " + 
                    "be used in auto-commit mode.");
        
        if (!(savepoint instanceof FBSavepoint))
            throw new SQLException(
                    "Specified savepoint was not obtained from this connection.");
        
        FBSavepoint fbSavepoint = (FBSavepoint)savepoint;
        
        if (!fbSavepoint.isValid())
            throw new SQLException("Savepoint is no longer valid.");
        try {
            getGDSHelper().executeImmediate(
                    "RELEASE SAVEPOINT " + fbSavepoint.getServerSavepointId() + " ONLY");
        } catch (GDSException ex) {
            throw new FBSQLException(ex);
        }
        
        fbSavepoint.invalidate();
        
        .remove(fbSavepoint);
    }

    
Invalidate all savepoints.
    protected synchronized void invalidateSavepoints() {
        Iterator iter = .iterator();
        while(iter.hasNext())
            ((FBSavepoint)iter.next()).invalidate();
        
        .clear();
    }    
    //-------------------------------------------
    //Borrowed from javax.resource.cci.Connection

    
Returns a FBLocalTransaction instance that enables a component to demarcate resource manager local transactions on this connection.
    public synchronized FirebirdLocalTransaction getLocalTransaction() {
        if ( == null)
             = new FBLocalTransaction(this);
        return ;
    }
    // java.sql.Wrapper interface
    
    public boolean isWrapperFor(Class<?> ifacethrows SQLException {
        return iface != null && iface.isAssignableFrom(FBConnection.class);
    }
    public <T> T unwrap(Class<T> ifacethrows SQLException {
        if (!isWrapperFor(iface))
            throw new FBDriverNotCapableException();
        
        return iface.cast(this);
    }
    public void setSchema(String schemathrows SQLException {
        // Ignore: no schema support
        checkValidity();
    }
    public String getSchema() throws SQLException {
        checkValidity();
        return null;
    }
    //package methods

    
Check if this connection is currently involved in a transaction
    public boolean inTransaction() throws SQLException {
        try {
            return getGDSHelper().inTransaction();
        } catch(GDSException ex) {
            throw new FBSQLException(ex);
        }
    }
   
    
Get the encoding that is being used for this connection.

Returns:
The name of the encoding used
    public String getIscEncoding() throws SQLException {
        try {
            return getGDSHelper().getIscEncoding();
        } catch(GDSException ex) {
            throw new FBSQLException(ex);
        }
    }
	 protected synchronized void addWarning(SQLWarning warning){
		 if ( == null)
			  = warning;
		 else{
			 SQLWarning lastWarning = ;
			 while (lastWarning.getNextWarning() != null){
				 lastWarning = lastWarning.getNextWarning();
			 }
			 lastWarning.setNextWarning(warning);
		 }
	 }
     
     
Get warnings associated with this database connection.

Returns:
instance of java.sql.SQLWarning that is the first warning in a linked list of warnings.
     private SQLWarning getIscWarnings() throws SQLException {
         try {
             SQLWarning firstWarning = null;
             SQLWarning lastWarning = null;
             Iterator iter = getGDSHelper().getWarnings().iterator();
             while (iter.hasNext()) {
                 GDSException item = (GDSException)iter.next();
                 
                 FBSQLWarning warning = new FBSQLWarning(item);
                 if (firstWarning == null) {
                     firstWarning = warning;
                     lastWarning = firstWarning;
                 } else {
                    lastWarning.setNextWarning(warning);
                    lastWarning = warning;
                 }
             }
             return firstWarning;
         } catch(GDSException ex) {
             throw new FBSQLException(ex);
         }
     }
     
     
Clear warnings associated with this database connection.
     private void clearIscWarnings() throws SQLException {
         try {
             getGDSHelper().clearWarnings();
         } catch(GDSException ex) {
             throw new FBSQLException(ex);
         }
     }
	 
    public GDSHelper getGDSHelper() throws GDSException {
        if ( == null)
        return .getGDSHelper();
    }
    
    protected void finalize() throws Throwable {
        close();
    }
    
    protected class GeneratedKeysQuery extends AbstractGeneratedKeysQuery {
        protected GeneratedKeysQuery(String sqlint autoGeneratedKeysthrows SQLException {
            super(sqlautoGeneratedKeys);
        }
        
        protected GeneratedKeysQuery(String sqlint[] columnIndexesthrows SQLException {
            super(sqlcolumnIndexes);
        }
        
        protected GeneratedKeysQuery(String sqlString[] columnNamesthrows SQLException {
            super(sqlcolumnNames);
        }
        @Override
            return getMetaData();
        }
    }