SQLExec (Apache Ant API)
Description: declaration: package: org.apache.tools.ant.taskdefs, class: SQLExec

# Class SQLExec

java.lang.Object
org.apache.tools.ant.ProjectComponent
org.apache.tools.ant.Task
org.apache.tools.ant.taskdefs.JDBCTask
org.apache.tools.ant.taskdefs.SQLExec

All Implemented Interfaces:
  `Cloneable`

public class SQLExec extends JDBCTask
Executes a series of SQL statements on a database using JDBC.

Statements can either be read in from a text file using the src attribute or from between the enclosing SQL tags.

Multiple statements can be provided, separated by semicolons (or the defined delimiter). Individual lines within the statements can be commented using either --, // or REM at the start of the line.

The autocommit attribute specifies whether auto-commit should be turned on or off whilst executing the statements. If auto-commit is turned on each statement will be executed and committed. If it is turned off the statements will all be executed as one transaction.

The onerror attribute specifies how to proceed when an error occurs during the execution of one of the statements. The possible values are: continue execution, only show the error; stop execution and commit transaction; and abort execution and transaction and fail task.

Since:
  Ant 1.2

- ## Nested Class Summary

  Nested Classes
  Modifier and Type
  Class
  Description
  `static class`
  `SQLExec.DelimiterType`
  delimiters we support, "normal" and "row"
  `static class`
  `SQLExec.OnError`
  The action a task should perform on an error, one of "continue", "stop" and "abort"
  `class`
  `SQLExec.Transaction`
  Contains the definition of a new transaction element.

- ## Field Summary

  ### Fields inherited from class Task

  `target, taskName, taskType, wrapper`
  Modifier and Type
  Field
  Description
  `protected Target`
  `target`
  Deprecated.
  since 1.6.x.
  `protected String`
  `taskName`
  Deprecated.
  since 1.6.x.
  `protected String`
  `taskType`
  Deprecated.
  since 1.6.x.
  `protected RuntimeConfigurable`
  `wrapper`
  Deprecated.
  since 1.6.x.

  ### Fields inherited from class ProjectComponent

  `description, location, project`
  Modifier and Type
  Field
  Description
  `protected String`
  `description`
  Deprecated.
  since 1.6.x.
  `protected Location`
  `location`
  Deprecated.
  since 1.6.x.
  `protected Project`
  `project`
  Deprecated.
  since 1.6.x.

- ## Constructor Summary

  Constructors
  Constructor
  Description
  `SQLExec()`

- ## Method Summary

  Modifier and Type
  Method
  Description
  `void`
  `add(ResourceCollection rc)`
  Adds a collection of resources (nested element).
  `void`
  `addFileset(FileSet set)`
  Adds a set of files (nested fileset attribute).
  `void`
  `addText(String sql)`
  Set an inline SQL command to execute.
  `SQLExec.Transaction`
  `createTransaction()`
  Add a SQL transaction to execute
  `protected void`
  `execSQL(String sql, PrintStream out)`
  Exec the sql statement.
  `void`
  `execute()`
  Load the sql file and then execute it
  `protected Connection`
  `getConnection()`
  Caches the connection returned by the base class's getConnection method.
  `boolean`
  `getExpandProperties()`
  is property expansion inside inline text enabled?
  `protected Statement`
  `getStatement()`
  Creates and configures a Statement instance which is then cached for subsequent calls.
  `int`
  `lastDelimiterPosition(StringBuffer buf, String currentLine)`
  `protected void`
  `printResults(PrintStream out)`
  Deprecated.
  since 1.6.x.
  `protected void`
  `printResults(ResultSet rs, PrintStream out)`
  print any results in the result set.
  `protected void`
  `runStatements(Reader reader, PrintStream out)`
  read in lines and execute them
  `void`
  `setAppend(boolean append)`
  whether output should be appended to or overwrite an existing file.
  `void`
  `setCsvColumnSeparator(String s)`
  The column separator used when printing the results.
  `void`
  `setCsvQuoteCharacter(String s)`
  The character used to quote column values.
  `void`
  `setDelimiter(String delimiter)`
  Set the delimiter that separates SQL statements.
  `void`
  `setDelimiterType(SQLExec.DelimiterType delimiterType)`
  Set the delimiter type: "normal" or "row" (default "normal").
  `void`
  `setEncoding(String encoding)`
  Set the file encoding to use on the SQL files read in
  `protected final void`
  `setErrorProperty()`
  `void`
  `setErrorProperty(String errorProperty)`
  Property to set to "true" if a statement throws an error.
  `void`
  `setEscapeProcessing(boolean enable)`
  Set escape processing for statements.
  `void`
  `setExpandProperties(boolean expandProperties)`
  Enable property expansion inside nested text
  `void`
  `setForceCsvQuoteChar(boolean forceCsvQuoteChar)`
  Force the csv quote character
  `void`
  `setKeepformat(boolean keepformat)`
  whether or not format should be preserved.
  `void`
  `setOnerror(SQLExec.OnError action)`
  Action to perform when statement fails: continue, stop, or abort optional; default "abort"
  `void`
  `setOutput(File output)`
  Set the output file; optional, defaults to the Ant log.
  `void`
  `setOutput(Resource output)`
  Set the output Resource; optional, defaults to the Ant log.
  `void`
  `setOutputEncoding(String outputEncoding)`
  The encoding to use when writing the result to a resource.
  `void`
  `setPrint(boolean print)`
  Print result sets from the statements; optional, default false
  `void`
  `setRawBlobs(boolean rawBlobs)`
  Set whether to print raw BLOBs rather than their string (hex) representations.
  `protected final void`
  `setRowCountProperty(int rowCount)`
  `void`
  `setRowCountProperty(String rowCountProperty)`
  Sets a given property to the number of rows in the first statement that returned a row count.
  `void`
  `setShowheaders(boolean showheaders)`
  Print headers for result sets from the statements; optional, default true.
  `void`
  `setShowtrailers(boolean showtrailers)`
  Print trailing info (rows affected) for the SQL Addresses Bug/Request #27446
  `void`
  `setShowWarnings(boolean b)`
  whether to show SQLWarnings as WARN messages.
  `void`
  `setSrc(File srcFile)`
  Set the name of the SQL file to be run.
  `void`
  `setStrictDelimiterMatching(boolean b)`
  If false, delimiters will be searched for in a case-insensitive manner (i.e.
  `void`
  `setTreatWarningsAsErrors(boolean b)`
  Whether a warning is an error - in which case onError applies.
  `protected final void`
  `setWarningProperty()`
  `void`
  `setWarningProperty(String warningProperty)`
  Property to set to "true" if a statement produces a warning.

  ### Methods inherited from class JDBCTask

  `addConnectionProperty, createClasspath, getClasspath, getLoader, getLoaderMap, getPassword, getRdbms, getUrl, getUserId, getVersion, isAutocommit, isCaching, isValidRdbms, setAutocommit, setCaching, setClasspath, setClasspathRef, setDriver, setFailOnConnectionError, setPassword, setRdbms, setUrl, setUserid, setVersion`
  Modifier and Type
  Method
  Description
  `void`
  `addConnectionProperty(Property var)`
  Additional properties to put into the JDBC connection string.
  `Path`
  `createClasspath()`
  Add a path to the classpath for loading the driver.
  `Path`
  `getClasspath()`
  Gets the classpath.
  `protected AntClassLoader`
  `getLoader()`
  Get the classloader used to create a driver.
  `protected static Hashtable<String, AntClassLoader>`
  `getLoaderMap()`
  Get the cache of loaders and drivers.
  `String`
  `getPassword()`
  Gets the password.
  `String`
  `getRdbms()`
  Gets the rdbms.
  `String`
  `getUrl()`
  Gets the url.
  `String`
  `getUserId()`
  Gets the userId.
  `String`
  `getVersion()`
  Gets the version.
  `boolean`
  `isAutocommit()`
  Gets the autocommit.
  `void`
  `isCaching(boolean value)`
  Set the caching attribute.
  `protected boolean`
  `isValidRdbms(Connection conn)`
  Verify we are connected to the correct RDBMS
  `void`
  `setAutocommit(boolean autocommit)`
  Auto commit flag for database connection; optional, default false.
  `void`
  `setCaching(boolean enable)`
  Caching loaders / driver.
  `void`
  `setClasspath(Path classpath)`
  Sets the classpath for loading the driver.
  `void`
  `setClasspathRef(Reference r)`
  Set the classpath for loading the driver using the classpath reference.
  `void`
  `setDriver(String driver)`
  Class name of the JDBC driver; required.
  `void`
  `setFailOnConnectionError(boolean b)`
  whether the task should cause the build to fail if it cannot connect to the database.
  `void`
  `setPassword(String password)`
  Sets the password; required.
  `void`
  `setRdbms(String rdbms)`
  Execute task only if the lower case product name of the DB matches this
  `void`
  `setUrl(String url)`
  Sets the database connection URL; required.
  `void`
  `setUserid(String userId)`
  Set the user name for the connection; required.
  `void`
  `setVersion(String version)`
  Sets the version string, execute task only if rdbms version match; optional.

  ### Methods inherited from class Task

  `bindToOwner, getOwningTarget, getRuntimeConfigurableWrapper, getTaskName, getTaskType, getWrapper, handleErrorFlush, handleErrorOutput, handleFlush, handleInput, handleOutput, init, isInvalid, log, log, log, log, maybeConfigure, perform, reconfigure, setOwningTarget, setRuntimeConfigurableWrapper, setTaskName, setTaskType`
  Modifier and Type
  Method
  Description
  `final void`
  `bindToOwner(Task owner)`
  Bind a task to another; use this when configuring a newly created task to do work on behalf of another.
  `Target`
  `getOwningTarget()`
  Returns the container target of this task.
  `RuntimeConfigurable`
  `getRuntimeConfigurableWrapper()`
  Returns the wrapper used for runtime configuration.
  `String`
  `getTaskName()`
  Returns the name to use in logging messages.
  `String`
  `getTaskType()`
  Return the type of task.
  `protected RuntimeConfigurable`
  `getWrapper()`
  Return the runtime configurable structure for this task.
  `protected void`
  `handleErrorFlush(String output)`
  Handles an error line by logging it with the WARN priority.
  `protected void`
  `handleErrorOutput(String output)`
  Handles an error output by logging it with the WARN priority.
  `protected void`
  `handleFlush(String output)`
  Handles output by logging it with the INFO priority.
  `protected int`
  `handleInput(byte[] buffer, int offset, int length)`
  Handle an input request by this task.
  `protected void`
  `handleOutput(String output)`
  Handles output by logging it with the INFO priority.
  `void`
  `init()`
  Called by the project to let the task initialize properly.
  `protected final boolean`
  `isInvalid()`
  Has this task been marked invalid?
  `void`
  `log(String msg)`
  Logs a message with the default (INFO) priority.
  `void`
  `log(String msg, int msgLevel)`
  Logs a message with the given priority.
  `void`
  `log(String msg, Throwable t, int msgLevel)`
  Logs a message with the given priority.
  `void`
  `log(Throwable t, int msgLevel)`
  Logs a message with the given priority.
  `void`
  `maybeConfigure()`
  Configures this task - if it hasn't been done already.
  `final void`
  `perform()`
  Performs this task if it's still valid, or gets a replacement version and performs that otherwise.
  `void`
  `reconfigure()`
  Force the task to be reconfigured from its RuntimeConfigurable.
  `void`
  `setOwningTarget(Target target)`
  Sets the target container of this task.
  `void`
  `setRuntimeConfigurableWrapper(RuntimeConfigurable wrapper)`
  Sets the wrapper to be used for runtime configuration.
  `void`
  `setTaskName(String name)`
  Sets the name to use in logging messages.
  `void`
  `setTaskType(String type)`
  Sets the name with which the task has been invoked.

  ### Methods inherited from class ProjectComponent

  `clone, getDescription, getLocation, getProject, setDescription, setLocation, setProject`
  Modifier and Type
  Method
  Description
  `Object`
  `clone()`
  `String`
  `getDescription()`
  Returns the description of the current action.
  `Location`
  `getLocation()`
  Returns the file/location where this task was defined.
  `Project`
  `getProject()`
  Returns the project to which this component belongs.
  `void`
  `setDescription(String desc)`
  Sets a description of the current action.
  `void`
  `setLocation(Location location)`
  Sets the file/location where this task was defined.
  `void`
  `setProject(Project project)`
  Sets the project object of this component.

  ### Methods inherited from class Object

  `equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait`

- ## Constructor Details

  - ### SQLExec

    public SQLExec()

- ## Method Details

  - ### setSrc

    public void setSrc(File srcFile)
    Set the name of the SQL file to be run. Required unless statements are enclosed in the build file
    Parameters:
      `srcFile` - the file containing the SQL command.

  - ### setExpandProperties

    public void setExpandProperties(boolean expandProperties)
    Enable property expansion inside nested text
    Parameters:
      `expandProperties` - if true expand properties.
    Since:
      Ant 1.7

  - ### getExpandProperties

    public boolean getExpandProperties()
    is property expansion inside inline text enabled?
    Returns:
      true if properties are to be expanded.
    Since:
      Ant 1.7

  - ### addText

    public void addText(String sql)
    Set an inline SQL command to execute. NB: Properties are not expanded in this text unless `expandProperties` is set.
    Parameters:
      `sql` - an inline string containing the SQL command.

  - ### addFileset

    public void addFileset(FileSet set)
    Adds a set of files (nested fileset attribute).
    Parameters:
      `set` - a set of files contains SQL commands, each File is run in a separate transaction.

  - ### add

    public void add(ResourceCollection rc)
    Adds a collection of resources (nested element).
    Parameters:
      `rc` - a collection of resources containing SQL commands, each resource is run in a separate transaction.
    Since:
      Ant 1.7

  - ### createTransaction

    public SQLExec.Transaction createTransaction()
    Add a SQL transaction to execute
    Returns:
      a Transaction to be configured.

  - ### setEncoding

    public void setEncoding(String encoding)
    Set the file encoding to use on the SQL files read in
    Parameters:
      `encoding` - the encoding to use on the files

  - ### setDelimiter

    public void setDelimiter(String delimiter)
    Set the delimiter that separates SQL statements. Defaults to ";"; optional

    For example, set this to "go" and delimitertype to "ROW" for Sybase ASE or MS SQL Server.

    Parameters:
      `delimiter` - the separator.

  - ### setDelimiterType

    public void setDelimiterType(SQLExec.DelimiterType delimiterType)
    Set the delimiter type: "normal" or "row" (default "normal").

    The delimiter type takes two values - normal and row. Normal means that any occurrence of the delimiter terminate the SQL command whereas with row, only a line containing just the delimiter is recognized as the end of the command.

    Parameters:
      `delimiterType` - the type of delimiter - "normal" or "row".

  - ### setPrint

    public void setPrint(boolean print)
    Print result sets from the statements; optional, default false
    Parameters:
      `print` - if true print result sets.

  - ### setShowheaders

    public void setShowheaders(boolean showheaders)
    Print headers for result sets from the statements; optional, default true.
    Parameters:
      `showheaders` - if true print headers of result sets.

  - ### setShowtrailers

    public void setShowtrailers(boolean showtrailers)
    Print trailing info (rows affected) for the SQL Addresses Bug/Request #27446
    Parameters:
      `showtrailers` - if true prints the SQL rows affected
    Since:
      Ant 1.7

  - ### setOutput

    public void setOutput(File output)
    Set the output file; optional, defaults to the Ant log.
    Parameters:
      `output` - the output file to use for logging messages.

  - ### setOutput

    public void setOutput(Resource output)
    Set the output Resource; optional, defaults to the Ant log.
    Parameters:
      `output` - the output Resource to store results.
    Since:
      Ant 1.8

  - ### setOutputEncoding

    public void setOutputEncoding(String outputEncoding)
    The encoding to use when writing the result to a resource.

    Default's to the platform's default encoding

    Parameters:
      `outputEncoding` - the name of the encoding or null for the platform's default encoding
    Since:
      Ant 1.9.4

  - ### setAppend

    public void setAppend(boolean append)
    whether output should be appended to or overwrite an existing file. Defaults to false.
    Parameters:
      `append` - if true append to an existing file.
    Since:
      Ant 1.5

  - ### setOnerror

    public void setOnerror(SQLExec.OnError action)
    Action to perform when statement fails: continue, stop, or abort optional; default "abort"
    Parameters:
      `action` - the action to perform on statement failure.

  - ### setKeepformat

    public void setKeepformat(boolean keepformat)
    whether or not format should be preserved. Defaults to false.
    Parameters:
      `keepformat` - The keepformat to set

  - ### setEscapeProcessing

    public void setEscapeProcessing(boolean enable)
    Set escape processing for statements.
    Parameters:
      `enable` - if true enable escape processing, default is true.
    Since:
      Ant 1.6

  - ### setRawBlobs

    public void setRawBlobs(boolean rawBlobs)
    Set whether to print raw BLOBs rather than their string (hex) representations.
    Parameters:
      `rawBlobs` - whether to print raw BLOBs.
    Since:
      Ant 1.7.1

  - ### setStrictDelimiterMatching

    public void setStrictDelimiterMatching(boolean b)
    If false, delimiters will be searched for in a case-insensitive manner (i.e. delimiter="go" matches "GO") and surrounding whitespace will be ignored (delimiter="go" matches "GO ").
    Parameters:
      `b` - boolean
    Since:
      Ant 1.8.0

  - ### setShowWarnings

    public void setShowWarnings(boolean b)
    whether to show SQLWarnings as WARN messages.
    Parameters:
      `b` - boolean
    Since:
      Ant 1.8.0

  - ### setTreatWarningsAsErrors

    public void setTreatWarningsAsErrors(boolean b)
    Whether a warning is an error - in which case onError applies.
    Parameters:
      `b` - boolean
    Since:
      Ant 1.8.0

  - ### setCsvColumnSeparator

    public void setCsvColumnSeparator(String s)
    The column separator used when printing the results.

    Defaults to ","

    Parameters:
      `s` - String
    Since:
      Ant 1.8.0

  - ### setCsvQuoteCharacter

    public void setCsvQuoteCharacter(String s)
    The character used to quote column values.

    If set, columns that contain either the column separator or the quote character itself will be surrounded by the quote character. The quote character itself will be doubled if it appears inside of the column's value.

    If this value is not set (the default), no column values will be quoted, not even if they contain the column separator.

    Note: BLOB values will never be quoted.

    Defaults to "not set"

    Parameters:
      `s` - String
    Since:
      Ant 1.8.0

  - ### setErrorProperty

    public void setErrorProperty(String errorProperty)
    Property to set to "true" if a statement throws an error.
    Parameters:
      `errorProperty` - the name of the property to set in the event of an error.
    Since:
      Ant 1.8.0

  - ### setWarningProperty

    public void setWarningProperty(String warningProperty)
    Property to set to "true" if a statement produces a warning.
    Parameters:
      `warningProperty` - the name of the property to set in the event of a warning.
    Since:
      Ant 1.8.0

  - ### setRowCountProperty

    public void setRowCountProperty(String rowCountProperty)
    Sets a given property to the number of rows in the first statement that returned a row count.
    Parameters:
      `rowCountProperty` - String
    Since:
      Ant 1.8.0

  - ### setForceCsvQuoteChar

    public void setForceCsvQuoteChar(boolean forceCsvQuoteChar)
    Force the csv quote character
    Parameters:
      `forceCsvQuoteChar` - boolean

  - ### execute

    public void execute() throws BuildException
    Load the sql file and then execute it
    Overrides:
      `execute` in class `Task`
    Throws:
      `BuildException` - on error.

  - ### runStatements

    protected void runStatements(Reader reader, PrintStream out) throws SQLException, IOException
    read in lines and execute them
    Parameters:
      `reader` - the reader contains sql lines.
      `out` - the place to output results.
    Throws:
      `SQLException` - on sql problems
      `IOException` - on io problems

  - ### execSQL

    protected void execSQL(String sql, PrintStream out) throws SQLException
    Exec the sql statement.
    Parameters:
      `sql` - the SQL statement to execute
      `out` - the place to put output
    Throws:
      `SQLException` - on SQL problems

  - ### printResults

    @Deprecated protected void printResults(PrintStream out) throws SQLException
    Deprecated.
    since 1.6.x. Use `the two arg version` instead.
    print any results in the statement
    Parameters:
      `out` - the place to print results
    Throws:
      `SQLException` - on SQL problems.

  - ### printResults

    protected void printResults(ResultSet rs, PrintStream out) throws SQLException
    print any results in the result set.
    Parameters:
      `rs` - the resultset to print information about
      `out` - the place to print results
    Throws:
      `SQLException` - on SQL problems.
    Since:
      Ant 1.6.3

  - ### getConnection

    protected Connection getConnection()
    Caches the connection returned by the base class's getConnection method.

    Subclasses that need to provide a different connection than the base class would, should override this method but keep in mind that this class expects to get the same connection instance on consecutive calls.

    returns null if the connection does not connect to the expected RDBMS.

    Overrides:
      `getConnection` in class `JDBCTask`
    Returns:
      Connection the newly created connection or null if the connection failed and failOnConnectionError is false.

  - ### getStatement

    protected Statement getStatement() throws SQLException
    Creates and configures a Statement instance which is then cached for subsequent calls.

    Subclasses that want to provide different Statement instances, should override this method but keep in mind that this class expects to get the same connection instance on consecutive calls.

    Returns:
      Statement
    Throws:
      `SQLException` - if statement creation or processing fails

  - ### lastDelimiterPosition

    public int lastDelimiterPosition(StringBuffer buf, String currentLine)

  - ### setErrorProperty

    protected final void setErrorProperty()

  - ### setWarningProperty

    protected final void setWarningProperty()

  - ### setRowCountProperty

    protected final void setRowCountProperty(int rowCount)