1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package net.sourceforge.addam.selectexec;
20
21 import org.apache.tools.ant.BuildException;
22 import org.apache.tools.ant.taskdefs.JDBCTask;
23
24 import java.sql.*;
25 import java.util.ArrayList;
26 import java.util.Iterator;
27 import java.util.List;
28
29 /**
30 * This is a strange task, but it can be quite useful... it executes the given
31 * SQL and treats the results (the first column, specifically) as a new set of
32 * SQL which it then executes.
33 *
34 * @author TIM3
35 * @since Nov 30, 2004 9:07:45 PM
36 */
37 public class SelectExecTask extends JDBCTask {
38
39 private String text = "";
40 private int batchSize = 1;
41
42 /**
43 * sets the number of statements to execute simultaneously
44 *
45 * @param size
46 */
47 public void setBatchSize(int size) {
48 this.batchSize = size;
49 }
50
51 /**
52 * adds to the SQL statement
53 *
54 * @param text
55 */
56 public void addText(String text) {
57 this.text += text;
58 }
59
60 public void execute() throws BuildException {
61 try {
62 Connection conn = this.getConnection();
63 List resultSQL = new ArrayList();
64 log(text);
65 PreparedStatement select = conn.prepareStatement(text);
66 ResultSet results = select.executeQuery();
67 while (results.next()) {
68 resultSQL.add(results.getString(1));
69 }
70 Statement exec = conn.createStatement();
71 int i = 0;
72 for (Iterator it = resultSQL.iterator(); it.hasNext(); i++) {
73 String sql = it.next().toString();
74 if (i % batchSize == 0) {
75 exec.executeBatch();
76 exec.clearBatch();
77 }
78 log(sql);
79 exec.addBatch(sql);
80 }
81 exec.executeBatch();
82 conn.commit();
83 } catch (SQLException e) {
84 e.printStackTrace();
85 throw new BuildException("upgrade failed: " + e, e);
86 }
87 }
88 }