Browse Source

Allow sql task to write results to a file.

Submitted by:	Julian M. Savage <jsavage@fisci.com>


git-svn-id: https://svn.apache.org/repos/asf/ant/core/trunk@268031 13f79535-47bb-0310-9956-ffa450edef68
master
Conor MacNeill 25 years ago
parent
commit
2067d20b5c
1 changed files with 86 additions and 1 deletions
  1. +86
    -1
      src/main/org/apache/tools/ant/taskdefs/SQLExec.java

+ 86
- 1
src/main/org/apache/tools/ant/taskdefs/SQLExec.java View File

@@ -116,6 +116,21 @@ public class SQLExec extends Task {
* SQL input command
*/
private String sqlCommand = "";

/**
* Print SQL results.
*/
private boolean print = false;

/**
* Print header columns.
*/
private boolean showheaders = true;

/**
* Results Output file.
*/
private File output = null;
/**
* Set the name of the sql file to be run.
@@ -165,6 +180,27 @@ public class SQLExec extends Task {
public void setAutocommit(boolean autocommit) {
this.autocommit = autocommit;
}

/**
* Set the print flag.
*/
public void setPrint(boolean print) {
this.print = print;
}
/**
* Set the showheaders flag.
*/
public void setShowheaders(boolean showheaders) {
this.showheaders = showheaders;
}

/**
* Set the output file.
*/
public void setOutput(File output) {
this.output = output;
}
/**
* Load the sql file and then execute it
@@ -282,12 +318,16 @@ public class SQLExec extends Task {
/**
* Exec the sql statement.
*/
protected void execSQL(String sql) throws SQLException{
protected void execSQL(String sql) throws SQLException {
if (!statement.execute(sql)) {
log(statement.getUpdateCount()+" rows affected",
Project.MSG_VERBOSE);
}

if (print) {
printResults();
}

SQLWarning warning = conn.getWarnings();
while(warning!=null){
log(warning + " sql warning", Project.MSG_VERBOSE);
@@ -296,4 +336,49 @@ public class SQLExec extends Task {
conn.clearWarnings();
}

/**
* print any results in the statement.
*/
protected void printResults() throws java.sql.SQLException {
ResultSet rs = null;
PrintStream out = System.out;
try {
if (output != null) {
out = new PrintStream(new BufferedOutputStream(new FileOutputStream(output)));
}
while ((rs = statement.getResultSet()) != null) {
ResultSetMetaData md = rs.getMetaData();
int columnCount = md.getColumnCount();
StringBuffer line = new StringBuffer();
if (showheaders) {
for (int col = 1; col < columnCount; col++) {
line.append(md.getColumnName(col));
line.append(",");
}
line.append(md.getColumnName(columnCount));
out.println(line);
line.setLength(0);
}
while (rs.next()) {
for (int col = 1; col < columnCount; col++) {
line.append(rs.getString(col).trim());
line.append(",");
}
line.append(rs.getString(columnCount).trim());
out.println(line);
line.setLength(0);
}
statement.getMoreResults();
}
}
catch (IOException ioe) {
throw new BuildException("Error writing " + output.getAbsolutePath(), ioe, location);
}
finally {
if (out != null) {
out.close();
}
}
}

}

Loading…
Cancel
Save