KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > hsqldb > util > ScriptTool


1 /* Copyright (c) 2001-2005, The HSQL Development Group
2  * All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions are met:
6  *
7  * Redistributions of source code must retain the above copyright notice, this
8  * list of conditions and the following disclaimer.
9  *
10  * Redistributions in binary form must reproduce the above copyright notice,
11  * this list of conditions and the following disclaimer in the documentation
12  * and/or other materials provided with the distribution.
13  *
14  * Neither the name of the HSQL Development Group nor the names of its
15  * contributors may be used to endorse or promote products derived from this
16  * software without specific prior written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21  * ARE DISCLAIMED. IN NO EVENT SHALL HSQL DEVELOPMENT GROUP, HSQLDB.ORG,
22  * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
23  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
24  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
25  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
26  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
28  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  */

30
31
32 package org.hsqldb.util;
33
34 import java.io.BufferedReader JavaDoc;
35 import java.io.FileReader JavaDoc;
36 import java.sql.Connection JavaDoc;
37 import java.sql.DriverManager JavaDoc;
38 import java.sql.ResultSet JavaDoc;
39 import java.sql.ResultSetMetaData JavaDoc;
40 import java.sql.SQLException JavaDoc;
41 import java.sql.Statement JavaDoc;
42 import java.util.Properties JavaDoc;
43
44 import org.hsqldb.lib.java.JavaSystem;
45
46 // fredt@users 20011220 - patch 481239 by yfl@users - new class
47
// jrmaher@users 20020710 - support for batch mode
48

49 /**
50  * Script tool - command line tool to read in sql script and execute it.
51  *
52  *
53  * @version 1.7.0
54  */

55 public class ScriptTool {
56
57     private static Properties JavaDoc pProperties = new Properties JavaDoc();
58     private Connection JavaDoc cConn;
59     private Statement JavaDoc sStatement;
60     private boolean BATCH = true;
61     private String JavaDoc EKW = new String JavaDoc("go");
62     private boolean EOF = false;
63     private int ln = 0;
64
65     /**
66      * Main method
67      *
68      *
69      * @param arg
70      */

71     public static void main(String JavaDoc[] arg) {
72
73         for (int i = 0; i < arg.length; i++) {
74             String JavaDoc p = arg[i];
75
76             if (p.equals("-?")) {
77                 printHelp();
78                 System.exit(0);
79             }
80         }
81
82         ScriptTool tool = new ScriptTool();
83
84         tool.execute(arg);
85         System.exit(0);
86     } // end main
87

88     public void execute(String JavaDoc[] arg) {
89
90         for (int i = 0; i < arg.length; i++) {
91             String JavaDoc p = arg[i];
92
93             if (p.charAt(0) == '-') {
94                 pProperties.put(p.substring(1), arg[i + 1]);
95
96                 i++;
97             }
98         }
99
100         ln = 0;
101         EOF = false;
102
103         BufferedReader JavaDoc in = null;
104         Properties JavaDoc p = pProperties;
105         String JavaDoc driver = p.getProperty("driver", "org.hsqldb.jdbcDriver");
106         String JavaDoc url = p.getProperty("url", "jdbc:hsqldb:");
107         String JavaDoc database = p.getProperty("database", "test");
108         String JavaDoc user = p.getProperty("user", "sa");
109         String JavaDoc password = p.getProperty("password", "");
110         String JavaDoc script = p.getProperty("script", "st.sql");
111         boolean log = p.getProperty("log", "false").equalsIgnoreCase("true");
112
113         BATCH = p.getProperty("batch", "true").equalsIgnoreCase("true");
114
115         try {
116             if (log) {
117                 trace("driver = " + driver);
118                 trace("url = " + url);
119                 trace("database = " + database);
120                 trace("user = " + user);
121                 trace("password = " + password);
122                 trace("script = " + script);
123                 trace("log = " + log);
124                 trace("batch = " + BATCH);
125                 JavaSystem.setLogToSystem(true);
126             }
127
128             // As described in the JDBC FAQ:
129
// http://java.sun.com/products/jdbc/jdbc-frequent.html;
130
// Why doesn't calling class.forName() load my JDBC driver?
131
// There is a bug in the JDK 1.1.x that can cause Class.forName() to fail.
132
// new org.hsqldb.jdbcDriver();
133
Class.forName(driver).newInstance();
134
135             cConn = DriverManager.getConnection(url + database, user,
136                                                 password);
137             in = new BufferedReader JavaDoc(new FileReader JavaDoc(script));
138         } catch (Exception JavaDoc e) {
139             System.out.println("ScriptTool.init error: " + e.getMessage());
140             e.printStackTrace();
141         }
142
143         try {
144             sStatement = cConn.createStatement();
145
146             String JavaDoc sql;
147
148             while ((sql = fileToString(in)) != null) {
149                 if (sql.length() == 1) {
150                     continue;
151                 }
152
153                 if (log) {
154                     trace("SQL (" + ln + ") : "
155                           + sql.substring(0, sql.length() - 2));
156                 }
157
158                 sStatement.execute(sql);
159
160                 ResultSet JavaDoc results = sStatement.getResultSet();
161                 int updateCount = sStatement.getUpdateCount();
162
163                 if (updateCount == -1) {
164                     trace(toString(results));
165                 } else {
166                     trace("update count " + updateCount);
167                 }
168             }
169         } catch (SQLException JavaDoc e) {
170             System.out.println("SQL Error at line " + ln + ": " + e);
171         }
172
173         try {
174             cConn.close();
175             in.close();
176         } catch (Exception JavaDoc ce) {}
177     }
178
179     /**
180      * Translate ResultSet to String representation
181      * @param r
182      */

183     private String JavaDoc toString(ResultSet JavaDoc r) {
184
185         try {
186             if (r == null) {
187                 return "No Result";
188             }
189
190             ResultSetMetaData JavaDoc m = r.getMetaData();
191             int col = m.getColumnCount();
192             StringBuffer JavaDoc strbuf = new StringBuffer JavaDoc();
193
194             for (int i = 1; i <= col; i++) {
195                 strbuf = strbuf.append(m.getColumnLabel(i) + "\t");
196             }
197
198             strbuf = strbuf.append("\n");
199
200             while (r.next()) {
201                 for (int i = 1; i <= col; i++) {
202                     strbuf = strbuf.append(r.getString(i) + "\t");
203
204                     if (r.wasNull()) {
205                         strbuf = strbuf.append("(null)\t");
206                     }
207                 }
208
209                 strbuf = strbuf.append("\n");
210             }
211
212             return strbuf.toString();
213         } catch (SQLException JavaDoc e) {
214             return null;
215         }
216     }
217
218     /**
219      * Read file and convert it to string.
220      */

221     private String JavaDoc fileToString(BufferedReader JavaDoc in) {
222
223         if (EOF) {
224             return null;
225         }
226
227         EOF = true;
228
229         StringBuffer JavaDoc a = new StringBuffer JavaDoc();
230
231         try {
232             String JavaDoc line;
233
234             while ((line = in.readLine()) != null) {
235                 ln = ln + 1;
236
237                 if (BATCH) {
238                     if (line.startsWith("print ")) {
239                         trace("\n" + line.substring(5));
240
241                         continue;
242                     }
243
244                     if (line.equalsIgnoreCase(EKW)) {
245                         EOF = false;
246
247                         break;
248                     }
249                 }
250
251                 a.append(line);
252                 a.append('\n');
253             }
254
255             a.append('\n');
256
257             return a.toString();
258         } catch (Exception JavaDoc e) {
259             e.printStackTrace();
260
261             throw new RuntimeException JavaDoc(e.getMessage());
262         }
263     }
264
265     /**
266      * Method declaration
267      *
268      *
269      * @param s
270      */

271     private void trace(String JavaDoc s) {
272         System.out.println(s);
273     }
274
275     /**
276      * Method declaration
277      *
278      */

279     private static void printHelp() {
280
281         System.out.println(
282             "Usage: java ScriptTool [-options]\n"
283             + "where options include:\n"
284             + " -driver <classname> name of the driver class\n"
285             + " -url <name> first part of the jdbc url\n"
286             + " -database <name> second part of the jdbc url\n"
287             + " -user <name> username used for connection\n"
288             + " -password <name> password for this user\n"
289             + " -log <true/false> write log to system out\n"
290             + " -batch <true/false> allow go/print pseudo statements\n"
291             + " -script <script file> reads from script file\n");
292     }
293 }
294
Popular Tags