KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > mckoi > tools > JDBCQueryTool


1 /**
2  * com.mckoi.tools.JDBCQueryTool 18 Aug 2000
3  *
4  * Mckoi SQL Database ( http://www.mckoi.com/database )
5  * Copyright (C) 2000, 2001, 2002 Diehl and Associates, Inc.
6  *
7  * This program is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License
9  * Version 2 as published by the Free Software Foundation.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14  * GNU General Public License Version 2 for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * Version 2 along with this program; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
19  *
20  * Change Log:
21  *
22  *
23  */

24
25 package com.mckoi.tools;
26
27 import com.mckoi.jfccontrols.ResultSetTableModel;
28 import com.mckoi.jfccontrols.QueryAgent;
29 import com.mckoi.jfccontrols.Query;
30 import com.mckoi.util.CommandLine;
31 import java.sql.*;
32 import java.awt.*;
33 import java.awt.event.*;
34 import javax.swing.*;
35 import javax.swing.border.*;
36
37 /**
38  * A graphical interactive SQL query tool that allows for queries to be
39  * executed to a JDBC driver.
40  *
41  * @author Tobias Downer
42  */

43
44 public class JDBCQueryTool extends JComponent {
45
46   /**
47    * The agent used to make queries on the JDBC connection.
48    */

49   private QueryAgent query_agent;
50
51   /**
52    * The JTextArea where the query is entered.
53    */

54   private JTextArea query_text_area;
55
56   /**
57    * The JTable where the query result is printed.
58    */

59   private JTable result_table;
60
61   /**
62    * The ResultSetTableModel for the table model that contains our result set.
63    */

64   private ResultSetTableModel table_model;
65
66   /**
67    * The JLabel status bar at the bottom of the window.
68    */

69   private JLabel status_text;
70
71   /**
72    * Set to true if the table is auto resize (default).
73    */

74   protected JCheckBoxMenuItem auto_resize_result_table;
75
76   /**
77    * Total number of rows in the result.
78    */

79   private int total_row_count;
80
81   /**
82    * The time it took to execute the query in milliseconds.
83    */

84   private int query_time = -1;
85
86   /**
87    * Constructs the JComponent.
88    */

89   public JDBCQueryTool(QueryAgent in_query_agent) {
90     this.query_agent = in_query_agent;
91
92     // --- Layout ---
93

94     // Toggle auto result columns.
95

96     auto_resize_result_table = new JCheckBoxMenuItem("Auto Resize Columns");
97     auto_resize_result_table.setSelected(true);
98     auto_resize_result_table.addActionListener(new ActionListener() {
99       public void actionPerformed(ActionEvent evt) {
100         if (auto_resize_result_table.isSelected()) {
101           result_table.setAutoResizeMode(
102                                      JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS);
103         }
104         else {
105           result_table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
106         }
107       }
108     });
109
110     // Main window
111

112     setLayout(new BorderLayout());
113     setBorder(new EmptyBorder(2, 2, 2, 2));
114
115     JPanel query_area = new JPanel();
116     query_area.setLayout(new BorderLayout());
117
118     // Mono-space font.
119
Font mono_font = new Font("MonoSpaced", Font.PLAIN, 12);
120
121     // The query text area
122
query_text_area = new JTextArea(7, 80);
123     query_text_area.setFont(mono_font);
124
125     // The execute and cancel query button
126
final JButton execute = new JButton("Run Query");
127     final JButton stop = new JButton("Stop Query");
128     stop.setEnabled(false);
129     JPanel button_bar = new JPanel();
130     button_bar.setLayout(new FlowLayout());
131     button_bar.add(execute);
132     button_bar.add(stop);
133
134     // The query area
135
query_area.add(new JScrollPane(query_text_area), BorderLayout.CENTER);
136     query_area.add(button_bar, BorderLayout.SOUTH);
137
138     table_model = new ResultSetTableModel();
139     table_model.setPreserveTableStructure(true);
140     result_table = new JTable(table_model);
141     JScrollPane scrolly_result_table = new JScrollPane(result_table);
142     scrolly_result_table.setPreferredSize(new Dimension(650, 450));
143
144     // The status bar.
145
status_text = new JLabel(" ");
146     status_text.setFont(mono_font);
147     status_text.setBorder(new BevelBorder(BevelBorder.LOWERED));
148
149     // Make the split pane
150
JSplitPane split_pane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
151     split_pane.setTopComponent(query_area);
152     split_pane.setBottomComponent(scrolly_result_table);
153
154     add(split_pane, BorderLayout.CENTER);
155
156     add(status_text, BorderLayout.SOUTH);
157
158     // --- Actions ---
159

160     execute.addActionListener(new ActionListener() {
161       public void actionPerformed(ActionEvent evt) {
162         try {
163
164           stop.setEnabled(true);
165           execute.setEnabled(false);
166
167           Query query = new Query(query_text_area.getText());
168           long time_start = System.currentTimeMillis();
169           ResultSet result_set = query_agent.executeQuery(query);
170           query_time = (int) (System.currentTimeMillis() - time_start);
171
172           // Scroll the result view to the top and update the model
173
result_table.scrollRectToVisible(new Rectangle(0, 0, 1, 1));
174           table_model.updateResultSet(result_set);
175
176           total_row_count = 0;
177           if (result_set.last()) {
178             total_row_count = result_set.getRow();
179           }
180           updateStatus();
181
182         }
183         catch (SQLException e) {
184           JOptionPane.showMessageDialog(JDBCQueryTool.this,
185                       e.getMessage(), "SQL Error", JOptionPane.ERROR_MESSAGE);
186           e.printStackTrace();
187         }
188         catch (InterruptedException JavaDoc e) {
189           System.err.println("Query cancelled.");
190         }
191         stop.setEnabled(false);
192         execute.setEnabled(true);
193       }
194     });
195
196     stop.addActionListener(new ActionListener() {
197       public void actionPerformed(ActionEvent evt) {
198         query_agent.cancelQuery();
199       }
200     });
201
202
203   }
204
205   /**
206    * Constructs the JComponent.
207    */

208   public JDBCQueryTool(Connection connection) {
209     this(new QueryAgent(connection));
210   }
211
212   /**
213    * Updates the status bar.
214    */

215   private void updateStatus() {
216     StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
217     buf.append("Query Time: ");
218     buf.append((double) query_time / 1000.0);
219     buf.append(" seconds. Row Count: ");
220     buf.append(total_row_count);
221     status_text.setText(new String JavaDoc(buf));
222   }
223
224   // ----- Static methods -----
225

226   /**
227    * The number of query windows we have open.
228    */

229   private static int query_window_count = 0;
230
231   /**
232    * Creates a new JDBC Query Tool window. Use this method to open a new
233    * query window in a JFrame to the database.
234    *
235    * @param connection the connection to the database
236    * @param close_connection_on_close if true the JDBC Connection is closed
237    * when the last query tool window is closed.
238    * @param system_exit_on_close if true the JVM will shut down when the last
239    * query tool window is closed.
240    */

241   public static void createNewWindow(final Connection connection,
242                                      final boolean close_connection_on_close,
243                                      final boolean system_exit_on_close) {
244     // Increment the count of windows open.
245
++query_window_count;
246
247     // The QueryAgent for this frame.
248
final QueryAgent query_agent = new QueryAgent(connection);
249
250     // Make the window,
251
final JFrame frame = new JFrame("Mckoi JDBC Query Tool");
252
253     // The action to close this window,
254
final Action close_action = new AbstractAction("Exit") {
255       public void actionPerformed(ActionEvent evt) {
256         frame.dispose();
257         // Decrement the count of windows open.
258
--query_window_count;
259         // If last window closed then close the connection and exit back to the
260
// system.
261
if (query_window_count == 0) {
262           if (close_connection_on_close) {
263             try {
264               connection.close();
265             }
266             catch (SQLException e) {
267               System.err.println("SQL Exception on close: " +
268                                  e.getMessage());
269             }
270           }
271           if (system_exit_on_close) {
272             System.exit(0);
273           }
274         }
275       }
276     };
277
278     // The action to clone this window
279
final Action clone_action = new AbstractAction("New Window") {
280       public void actionPerformed(ActionEvent evt) {
281         createNewWindow(connection,
282                         close_connection_on_close, system_exit_on_close);
283       }
284     };
285
286     // --- The layout ---
287

288     Container c = frame.getContentPane();
289     c.setLayout(new BorderLayout());
290     JDBCQueryTool query_tool = new JDBCQueryTool(query_agent);
291     c.add(query_tool, BorderLayout.CENTER);
292
293     // Set the menu bar for the window.
294
JMenuBar menu_bar = new JMenuBar();
295     JMenu file = new JMenu("File");
296     file.add(clone_action);
297     file.addSeparator();
298     file.add(close_action);
299     menu_bar.add(file);
300
301     JMenu options = new JMenu("Options");
302     options.add(query_tool.auto_resize_result_table);
303     menu_bar.add(options);
304
305     frame.setJMenuBar(menu_bar);
306
307     // Pack and show the window.
308
frame.pack();
309     frame.show();
310
311     // If frame is closed then perform the close action.
312
frame.addWindowListener(new WindowAdapter() {
313       public void windowClosing(WindowEvent evt) {
314         close_action.actionPerformed(null);
315       }
316     });
317
318   }
319
320   /**
321    * Prints the syntax to System.out.
322    */

323   private static void printSyntax() {
324     System.out.println("JDBCQueryTool [-jdbc JDBC_Driver_Class] [-url JDBC_URL] -u username -p password");
325   }
326
327   /**
328    * Application start point.
329    */

330   public static void main(String JavaDoc[] args) {
331     CommandLine cl = new CommandLine(args);
332
333     String JavaDoc driver = cl.switchArgument("-jdbc", "com.mckoi.JDBCDriver");
334     String JavaDoc url = cl.switchArgument("-url", "jdbc:mckoi:");
335     String JavaDoc username = cl.switchArgument("-u");
336     String JavaDoc password = cl.switchArgument("-p");
337
338     if (username == null) {
339       System.out.println("Please provide a username");
340       System.out.println();
341       printSyntax();
342     }
343     else if (password == null) {
344       System.out.println("Please provide a password");
345       System.out.println();
346       printSyntax();
347     }
348     else {
349
350       try {
351         System.out.println("Using JDBC Driver: " + driver);
352
353         // Register the driver.
354
Class.forName(driver).newInstance();
355
356         // Make a connection to the server.
357
final Connection connection =
358                          DriverManager.getConnection(url, username, password);
359
360         System.out.println("Connection established to: " + url);
361
362         // Invoke the tool on the swing event dispatch thread.
363
SwingUtilities.invokeLater(new Runnable JavaDoc() {
364           public void run() {
365             createNewWindow(connection, true, true);
366           }
367         });
368
369       }
370       catch (ClassNotFoundException JavaDoc e) {
371         System.out.println("JDBC Driver not found.");
372       }
373       catch (Exception JavaDoc e) {
374         e.printStackTrace();
375       }
376
377     }
378
379   }
380
381 }
382
Popular Tags