KickJava   Java API By Example, From Geeks To Geeks.

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


1 /* Copyright (c) 1995-2000, The Hypersonic SQL 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 Hypersonic SQL 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 THE HYPERSONIC SQL GROUP,
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  * This software consists of voluntary contributions made by many individuals
31  * on behalf of the Hypersonic SQL Group.
32  *
33  *
34  * For work added by the HSQL Development Group:
35  *
36  * Copyright (c) 2001-2005, The HSQL Development Group
37  * All rights reserved.
38  *
39  * Redistribution and use in source and binary forms, with or without
40  * modification, are permitted provided that the following conditions are met:
41  *
42  * Redistributions of source code must retain the above copyright notice, this
43  * list of conditions and the following disclaimer.
44  *
45  * Redistributions in binary form must reproduce the above copyright notice,
46  * this list of conditions and the following disclaimer in the documentation
47  * and/or other materials provided with the distribution.
48  *
49  * Neither the name of the HSQL Development Group nor the names of its
50  * contributors may be used to endorse or promote products derived from this
51  * software without specific prior written permission.
52  *
53  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
54  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
55  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
56  * ARE DISCLAIMED. IN NO EVENT SHALL HSQL DEVELOPMENT GROUP, HSQLDB.ORG,
57  * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
58  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
59  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
60  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
61  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
62  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
63  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
64  */

65
66
67 package org.hsqldb.util;
68
69 import java.applet.Applet JavaDoc;
70 import java.io.BufferedReader JavaDoc;
71 import java.io.FileReader JavaDoc;
72 import java.io.IOException JavaDoc;
73 import java.sql.Connection JavaDoc;
74 import java.sql.DriverManager JavaDoc;
75 import java.sql.ResultSet JavaDoc;
76 import java.sql.ResultSetMetaData JavaDoc;
77 import java.sql.SQLException JavaDoc;
78 import java.sql.Statement JavaDoc;
79 import java.util.Properties JavaDoc;
80 import java.awt.BorderLayout JavaDoc;
81 import java.awt.Button JavaDoc;
82 import java.awt.Choice JavaDoc;
83 import java.awt.Event JavaDoc;
84 import java.awt.Font JavaDoc;
85 import java.awt.Frame JavaDoc;
86 import java.awt.Label JavaDoc;
87 import java.awt.Menu JavaDoc;
88 import java.awt.MenuBar JavaDoc;
89 import java.awt.Panel JavaDoc;
90 import java.awt.SystemColor JavaDoc;
91 import java.awt.TextArea JavaDoc;
92 import java.awt.event.ActionEvent JavaDoc;
93 import java.awt.event.ActionListener JavaDoc;
94 import java.awt.event.WindowEvent JavaDoc;
95 import java.awt.event.WindowListener JavaDoc;
96
97 import org.hsqldb.lib.java.JavaSystem;
98
99 /**
100  * Simple demonstration applet
101  *
102  *
103  * @author Thomas Mueller (Hypersonic SQL Group)
104  * @version 1.7.0
105  * @since Hypersonic SQL
106  */

107 public class QueryTool extends Applet JavaDoc
108 implements WindowListener JavaDoc, ActionListener JavaDoc {
109
110     static Properties JavaDoc pProperties = new Properties JavaDoc();
111     boolean bApplication;
112
113     /**
114      * You can start QueryTool without a browser and applet
115      * using using this method. Type 'java QueryTool' to start it.
116      * This is necessary if you want to use the standalone version
117      * because appletviewer and internet browers do not allow the
118      * applet to write to disk.
119      */

120     static Frame JavaDoc fMain;
121
122     /**
123      * Method declaration
124      *
125      *
126      * @param arg
127      */

128     public static void main(String JavaDoc[] arg) {
129
130         fMain = new Frame JavaDoc("Query Tool");
131
132         QueryTool q = new QueryTool();
133
134         q.bApplication = true;
135
136         for (int i = 0; i < arg.length; i++) {
137             String JavaDoc p = arg[i];
138
139             if (p.equals("-?")) {
140                 printHelp();
141             }
142
143             if (p.charAt(0) == '-') {
144                 pProperties.put(p.substring(1), arg[i + 1]);
145
146                 i++;
147             }
148         }
149
150         q.init();
151         q.start();
152         fMain.add("Center", q);
153
154         MenuBar JavaDoc menu = new MenuBar JavaDoc();
155         Menu JavaDoc file = new Menu JavaDoc("File");
156
157         file.add("Exit");
158         file.addActionListener(q);
159         menu.add(file);
160         fMain.setMenuBar(menu);
161         fMain.setSize(500, 400);
162         fMain.show();
163         fMain.addWindowListener(q);
164     }
165
166     Connection JavaDoc cConn;
167     Statement JavaDoc sStatement;
168
169     /**
170      * Initializes the window and the database and inserts some test data.
171      */

172     public void init() {
173
174         initGUI();
175
176         Properties JavaDoc p = pProperties;
177
178         if (!bApplication) {
179
180             // default for applets is in-memory (.)
181
p.put("database", ".");
182
183             try {
184
185                 // but it may be also a HTTP connection (http://)
186
// try to use url as provided on the html page as parameter
187
pProperties.put("database", getParameter("database"));
188             } catch (Exception JavaDoc e) {}
189         }
190
191         String JavaDoc driver = p.getProperty("driver", "org.hsqldb.jdbcDriver");
192         String JavaDoc url = p.getProperty("url", "jdbc:hsqldb:");
193         String JavaDoc database = p.getProperty("database", ".");
194         String JavaDoc user = p.getProperty("user", "sa");
195         String JavaDoc password = p.getProperty("password", "");
196         boolean test = p.getProperty("test", "true").equalsIgnoreCase("true");
197         boolean log = p.getProperty("log", "true").equalsIgnoreCase("true");
198
199         try {
200             if (log) {
201                 trace("driver =" + driver);
202                 trace("url =" + url);
203                 trace("database=" + database);
204                 trace("user =" + user);
205                 trace("password=" + password);
206                 trace("test =" + test);
207                 trace("log =" + log);
208                 JavaSystem.setLogToSystem(true);
209             }
210
211             // As described in the JDBC FAQ:
212
// http://java.sun.com/products/jdbc/jdbc-frequent.html;
213
// Why doesn't calling class.forName() load my JDBC driver?
214
// There is a bug in the JDK 1.1.x that can cause Class.forName() to fail.
215
// new org.hsqldb.jdbcDriver();
216
Class.forName(driver).newInstance();
217
218             cConn = DriverManager.getConnection(url + database, user,
219                                                 password);
220         } catch (Exception JavaDoc e) {
221             System.out.println("QueryTool.init: " + e.getMessage());
222             e.printStackTrace();
223         }
224
225         sRecent = new String JavaDoc[iMaxRecent];
226         iRecent = 0;
227
228         try {
229             sStatement = cConn.createStatement();
230         } catch (SQLException JavaDoc e) {
231             System.out.println("Exception: " + e);
232         }
233
234         if (test) {
235             insertTestData();
236         }
237
238         txtCommand.requestFocus();
239     }
240
241     /**
242      * Method declaration
243      *
244      *
245      * @param s
246      */

247     void trace(String JavaDoc s) {
248         System.out.println(s);
249     }
250
251     /**
252      * This is function handles the events when a button is clicked or
253      * when the used double-clicked on the listbox of recent commands.
254      */

255     public boolean action(Event JavaDoc evt, Object JavaDoc arg) {
256
257         String JavaDoc s = arg.toString();
258
259         if (s.equals("Execute")) {
260             String JavaDoc sCmd = txtCommand.getText();
261             String JavaDoc[] g = new String JavaDoc[1];
262
263             try {
264                 sStatement.execute(sCmd);
265
266                 int r = sStatement.getUpdateCount();
267
268                 if (r == -1) {
269                     formatResultSet(sStatement.getResultSet());
270                 } else {
271                     g[0] = "update count";
272
273                     gResult.setHead(g);
274
275                     g[0] = String.valueOf(r);
276
277                     gResult.addRow(g);
278                 }
279
280                 setRecent(txtCommand.getText());
281             } catch (SQLException JavaDoc e) {
282                 g[0] = "SQL Error";
283
284                 gResult.setHead(g);
285
286                 g[0] = e.getMessage();
287
288                 gResult.addRow(g);
289             }
290
291             gResult.repaint();
292             txtCommand.selectAll();
293             txtCommand.requestFocus();
294         } else if (s.equals("Script")) {
295             String JavaDoc sScript = getScript();
296
297             txtCommand.setText(sScript);
298             txtCommand.selectAll();
299             txtCommand.requestFocus();
300         } else if (s.equals("Import")) {
301             String JavaDoc sImport = getImport();
302
303             txtCommand.setText(sImport);
304             txtCommand.selectAll();
305             txtCommand.requestFocus();
306         } else if (s.equals("Exit")) {
307             System.exit(0);
308         } else { // recent
309
txtCommand.setText(s);
310         }
311
312         return true;
313     }
314
315     /**
316      * Method declaration
317      *
318      *
319      * @param r
320      */

321     void formatResultSet(ResultSet JavaDoc r) {
322
323         try {
324             ResultSetMetaData JavaDoc m = r.getMetaData();
325             int col = m.getColumnCount();
326             String JavaDoc[] h = new String JavaDoc[col];
327
328             for (int i = 1; i <= col; i++) {
329                 h[i - 1] = m.getColumnLabel(i);
330             }
331
332             gResult.setHead(h);
333
334             while (r.next()) {
335                 for (int i = 1; i <= col; i++) {
336                     h[i - 1] = r.getString(i);
337
338                     if (r.wasNull()) {
339                         h[i - 1] = "(null)";
340                     }
341                 }
342
343                 gResult.addRow(h);
344             }
345         } catch (SQLException JavaDoc e) {}
346     }
347
348     /**
349      * Method declaration
350      *
351      *
352      * @return
353      */

354     String JavaDoc getScript() {
355
356         ResultSet JavaDoc rResult = null;
357
358         try {
359             rResult = sStatement.executeQuery("SCRIPT");
360
361             StringBuffer JavaDoc a = new StringBuffer JavaDoc();
362
363             while (rResult.next()) {
364                 a.append(rResult.getString(1));
365                 a.append('\n');
366             }
367
368             a.append('\n');
369
370             return a.toString();
371         } catch (SQLException JavaDoc e) {
372             return "";
373         } finally {
374             if (rResult != null) {
375                 try {
376                     rResult.close();
377                 } catch (Exception JavaDoc e) {}
378             }
379         }
380     }
381
382     /**
383      * Method declaration
384      *
385      *
386      * @return
387      */

388     String JavaDoc getImport() {
389
390         StringBuffer JavaDoc a = new StringBuffer JavaDoc();
391         String JavaDoc filename = "import.sql";
392         BufferedReader JavaDoc in = null;
393
394         try {
395             in = new BufferedReader JavaDoc(new FileReader JavaDoc(filename));
396
397             String JavaDoc line;
398
399             while ((line = in.readLine()) != null) {
400                 a.append(line);
401                 a.append('\n');
402             }
403
404             a.append('\n');
405             in.close();
406
407             return a.toString();
408         } catch (Exception JavaDoc e) {
409             if (in != null) {
410                 try {
411                     in.close();
412                 } catch (IOException JavaDoc e1) {}
413             }
414
415             return "";
416         }
417     }
418
419     /**
420      * Adds a String to the Listbox of recent commands.
421      */

422     private void setRecent(String JavaDoc s) {
423
424         for (int i = 0; i < iMaxRecent; i++) {
425             if (s.equals(sRecent[i])) {
426                 return;
427             }
428         }
429
430         if (sRecent[iRecent] != null) {
431             choRecent.remove(sRecent[iRecent]);
432         }
433
434         sRecent[iRecent] = s;
435         iRecent = (iRecent + 1) % iMaxRecent;
436
437         choRecent.addItem(s);
438     }
439
440     String JavaDoc[] sRecent;
441     static int iMaxRecent = 24;
442     int iRecent;
443     TextArea JavaDoc txtCommand;
444     Button JavaDoc butExecute, butScript;
445     Button JavaDoc butImport;
446     Choice JavaDoc choRecent;
447     Grid gResult;
448
449     /**
450      * Create the graphical user interface. This is AWT code.
451      */

452     private void initGUI() {
453
454         // all panels
455
Panel JavaDoc pQuery = new Panel JavaDoc();
456         Panel JavaDoc pCommand = new Panel JavaDoc();
457         Panel JavaDoc pButton = new Panel JavaDoc();
458         Panel JavaDoc pRecent = new Panel JavaDoc();
459         Panel JavaDoc pResult = new Panel JavaDoc();
460         Panel JavaDoc pBorderWest = new Panel JavaDoc();
461         Panel JavaDoc pBorderEast = new Panel JavaDoc();
462         Panel JavaDoc pBorderSouth = new Panel JavaDoc();
463
464         pQuery.setLayout(new BorderLayout JavaDoc());
465         pCommand.setLayout(new BorderLayout JavaDoc());
466         pButton.setLayout(new BorderLayout JavaDoc());
467         pRecent.setLayout(new BorderLayout JavaDoc());
468         pResult.setLayout(new BorderLayout JavaDoc());
469         pBorderWest.setBackground(SystemColor.control);
470         pBorderSouth.setBackground(SystemColor.control);
471         pBorderEast.setBackground(SystemColor.control);
472
473         // labels
474
Label JavaDoc lblCommand = new Label JavaDoc(" Command", Label.LEFT);
475         Label JavaDoc lblRecent = new Label JavaDoc(" Recent", Label.LEFT);
476         Label JavaDoc lblResult = new Label JavaDoc(" Result", Label.LEFT);
477
478         lblCommand.setBackground(SystemColor.control);
479         lblRecent.setBackground(SystemColor.control);
480         lblResult.setBackground(SystemColor.control);
481
482         // buttons
483
butExecute = new Button JavaDoc("Execute");
484         butScript = new Button JavaDoc("Script");
485         butImport = new Button JavaDoc("Import");
486
487         pButton.add("South", butScript);
488         pButton.add("Center", butExecute);
489         pButton.add("North", butImport);
490
491         // command - textarea
492
Font JavaDoc fFont = new Font JavaDoc("Dialog", Font.PLAIN, 12);
493
494         txtCommand = new TextArea JavaDoc(5, 40);
495
496         txtCommand.setFont(fFont);
497
498         // recent - choice
499
choRecent = new Choice JavaDoc();
500
501         // result - grid
502
gResult = new Grid();
503
504         // combine it
505
setLayout(new BorderLayout JavaDoc());
506         pRecent.add("Center", choRecent);
507         pRecent.add("North", lblRecent);
508         pCommand.add("North", lblCommand);
509         pCommand.add("East", pButton);
510         pCommand.add("Center", txtCommand);
511         pCommand.add("South", pRecent);
512         pResult.add("North", lblResult);
513         pResult.add("Center", gResult);
514         pQuery.add("North", pCommand);
515         pQuery.add("Center", pResult);
516         add("Center", pQuery);
517         add("West", pBorderWest);
518         add("East", pBorderEast);
519         add("South", pBorderSouth);
520
521         // fredt@users 20011210 - patch 450412 by elise@users
522
doLayout();
523     }
524
525     static String JavaDoc[] sTestData = {
526         "drop table Place if exists",
527         "create table Place (Code integer,Name varchar(255))",
528         "create index iCode on Place (Code)", "delete from place",
529         "insert into Place values (4900,'Langenthal')",
530         "insert into Place values (8000,'Zurich')",
531         "insert into Place values (3000,'Berne')",
532         "insert into Place values (1200,'Geneva')",
533         "insert into Place values (6900,'Lugano')",
534         "drop table Customer if exists",
535         "create table Customer (Nr integer,Name varchar(255),Place integer)",
536         "create index iNr on Customer (Nr)", "delete from Customer",
537         "insert into Customer values (1,'Meier',3000)",
538         "insert into Customer values (2,'Mueller',8000)",
539         "insert into Customer values (3,'Devaux',1200)",
540         "insert into Customer values (4,'Rossi',6900)",
541         "insert into Customer values (5,'Rickli',3000)",
542         "insert into Customer values (6,'Graf',3000)",
543         "insert into Customer values (7,'Mueller',4900)",
544         "insert into Customer values (8,'May',1200)",
545         "insert into Customer values (9,'Berger',8000)",
546         "insert into Customer values (10,'D''Ascoli',6900)",
547         "insert into Customer values (11,'Padruz',1200)",
548         "insert into Customer values (12,'Hug',4900)"
549     };
550
551     /**
552      * Method declaration
553      *
554      */

555     void insertTestData() {
556
557         for (int i = 0; i < sTestData.length; i++) {
558             try {
559                 sStatement.executeQuery(sTestData[i]);
560             } catch (SQLException JavaDoc e) {
561                 System.out.println("Exception: " + e);
562             }
563         }
564
565         setRecent("select * from place");
566         setRecent("select * from Customer");
567         setRecent("select * from Customer where place<>3000");
568         setRecent("select * from place where code>3000 or code=1200");
569         setRecent("select * from Customer where nr<=8\nand name<>'Mueller'");
570         setRecent("update Customer set name='Russi'\nwhere name='Rossi'");
571         setRecent("delete from Customer where place=8000");
572         setRecent("insert into place values(3600,'Thun')");
573         setRecent("drop index Customer.iNr");
574         setRecent("select * from Customer where name like '%e%'");
575         setRecent("select count(*),min(code),max(code),sum(code) from place");
576
577         String JavaDoc s = "select * from Customer,place\n"
578                    + "where Customer.place=place.code\n"
579                    + "and place.name='Berne'";
580
581         setRecent(s);
582         txtCommand.setText(s);
583         txtCommand.selectAll();
584     }
585
586     /**
587      * Method declaration
588      *
589      */

590     static void printHelp() {
591
592         System.out.println(
593             "Usage: java QueryTool [-options]\n" + "where options include:\n"
594             + " -driver <classname> name of the driver class\n"
595             + " -url <name> first part of the jdbc url\n"
596             + " -database <name> second part of the jdbc url\n"
597             + " -user <name> username used for connection\n"
598             + " -password <name> password for this user\n"
599             + " -test <true/false> insert test data\n"
600             + " -log <true/false> write log to system out");
601         System.exit(0);
602     }
603
604     /**
605      * Method declaration
606      *
607      *
608      * @param e
609      */

610     public void windowActivated(WindowEvent JavaDoc e) {}
611
612     /**
613      * Method declaration
614      *
615      *
616      * @param e
617      */

618     public void windowDeactivated(WindowEvent JavaDoc e) {}
619
620     /**
621      * Method declaration
622      *
623      *
624      * @param e
625      */

626     public void windowClosed(WindowEvent JavaDoc e) {}
627
628     /**
629      * Method declaration
630      *
631      *
632      * @param ev
633      */

634     public void windowClosing(WindowEvent JavaDoc ev) {
635
636         try {
637             cConn.close();
638         } catch (Exception JavaDoc e) {}
639
640         if (fMain != null) {
641             fMain.dispose();
642         }
643
644         System.exit(0);
645     }
646
647     /**
648      * Method declaration
649      *
650      *
651      * @param e
652      */

653     public void windowDeiconified(WindowEvent JavaDoc e) {}
654
655     /**
656      * Method declaration
657      *
658      *
659      * @param e
660      */

661     public void windowIconified(WindowEvent JavaDoc e) {}
662
663     /**
664      * Method declaration
665      *
666      *
667      * @param e
668      */

669     public void windowOpened(WindowEvent JavaDoc e) {}
670
671     /**
672      * Method declaration
673      *
674      *
675      * @param ev
676      */

677     public void actionPerformed(ActionEvent JavaDoc ev) {
678
679         String JavaDoc s = ev.getActionCommand();
680
681         if (s != null && s.equals("Exit")) {
682             windowClosing(null);
683         }
684     }
685 }
686
Popular Tags