Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 50 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
50
Dung lượng
1,4 MB
Nội dung
Chapter 7:Retrieving Data with SQL Queries
-249-
* CREATE statements
*/
class TableQueryFrame extends JInternalFrame{
protected JTable table;
protected JScrollPane tableScroller;
protected JTextArea SQLPane = new JTextArea();
protected JButton queryButton = new JButton("Execute Query");
protected DatabaseUtilities dbUtils;
protected String tableName = null;
protected String colNames[] = null;
protected String dataTypes[] = null;
protected String SQLQuery = null;
protected String SQLCommandRoot = "";
public TableQueryFrame(String tableName, DatabaseUtilities dbUtils){
System.out.println(tableName+", "+dbUtils);
setSize(600,400);
setLocation(10,10);
setClosable(true);
setMaximizable(true);
setIconifiable(true);
setResizable(true);
getContentPane().setLayout(new BorderLayout());
this.tableName=tableName;
this.dbUtils=dbUtils;
setTitle("Query "+tableName);
init();
setVisible(true);
}
// initialize the JInternalFrame
private void init(){
TEAMFLY
Team-Fly
®
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Chapter 7:Retrieving Data with SQL Queries
-250-
colNames = dbUtils.getColumnNames(tableName);
dataTypes = dbUtils.getDataTypes(tableName);
SQLQuery = "SELECT TOP 5 * FROM "+tableName;
Vector dataSet = dbUtils.executeQuery(SQLQuery);
table = createTable(colNames,dataSet);
JScrollPane sqlScroller = new JScrollPane(SQLPane);
tableScroller = new JScrollPane(table);
JSplitPane splitter = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
sqlScroller,tableScroller);
splitter.setDividerLocation(100);
getContentPane().add(splitter,BorderLayout.CENTER);
getContentPane().add(queryButton,BorderLayout.SOUTH);
queryButton.addActionListener(new ButtonListener());
}
protected JTable createTable(String[] colNames,Vector dataSet){
int nRows = dataSet.size();
String[][] rowData = new String[nRows][colNames.length];
for(int i=0;i<nRows;i++){
Vector row = (Vector)dataSet.elementAt(i);
for(int j=0;j<row.size();j++)
rowData[i][j]=((Object)row.elementAt(j)).toString();
}
JTable table = new JTable(rowData,colNames);
return table;
}
// Listener for the Query Button
class ButtonListener implements ActionListener{
public void actionPerformed(ActionEvent event){
SQLQuery = SQLPane.getText();
JViewport viewport = tableScroller.getViewport();
viewport.remove(table);
colNames = dbUtils.getColumnNamesUsingQuery(SQLQuery);
Vector dataSet = dbUtils.executeQuery(SQLQuery);
table = createTable(colNames,dataSet);
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Chapter 7:Retrieving Data with SQL Queries
-251-
viewport.add(table);
}
}
}
Changes to the DBManager class (Listing 7-4) are once again minimal, amounting to no more than
adding the hooks for the menu.
Listing 7-4: DBManager
package jdbc_bible.part2;
import java.awt.*;
import java.awt.event.*;
import java.util.Vector;
import javax.swing.*;
import javax.swing.event.*;
public class DBManager extends JFrame{
JMenuBar menuBar = new JMenuBar();
JDesktopPane desktop = new JDesktopPane();
String database = null;
String tableName = null;
String menuSelection = null;
TableBuilderFrame tableMaker = null;
TableEditFrame tableEditor = null; // added for Chapter 6
TableQueryFrame tableQuery = null; // added for Chapter 7
DatabaseUtilities dbUtils = null;
TableMenu tableMenu = new TableMenu();
EditMenu editMenu = new EditMenu(); // added for Chapter 6
ViewMenu viewMenu = new ViewMenu(); // added for Chapter 7
MenuListener menuListener = new MenuListener();
public DBManager(){
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Chapter 7:Retrieving Data with SQL Queries
-252 -
setJMenuBar(menuBar);
setTitle("Java Database Bible");
getContentPane().setLayout(new BorderLayout());
getContentPane().add(desktop,BorderLayout.CENTER);
setSize(new Dimension(480,320));
menuBar.add(tableMenu);
tableMenu.setMenuListener(menuListener);
menuBar.add(editMenu); // added for Chapter 6
editMenu.setMenuListener(menuListener);
menuBar.add(viewMenu); // added for Chapter 7
viewMenu.setMenuListener(menuListener);
setFont(new Font("Dialog",Font.PLAIN,18));
setVisible(true);
Font font = getGraphics().getFont();
System.out.println(font);
}
private void displayTableBuilderFrame(){
tableName = JOptionPane.showInputDialog(this,"Table:",
"Select table",JOptionPane.QUESTION_MESSAGE);
tableMaker = new TableBuilderFrame(tableName);
tableMaker.setCommandListener(new CommandListener());
desktop.add(tableMaker);
tableMaker.setVisible(true);
}
private void displayTableEditFrame(){ // added for Chapter 6
tableName = JOptionPane.showInputDialog(this,"Table:",
"Select table",JOptionPane.QUESTION_MESSAGE);
tableEditor = new TableEditFrame(tableName,dbUtils);
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Chapter 7:Retrieving Data with SQL Queries
-253 -
desktop.add(tableEditor);
tableEditor.setVisible(true);
}
private void displayTableQueryFrame(){ // added for Chapter 7
tableName = JOptionPane.showInputDialog(this,"Table:",
"Select table",JOptionPane.QUESTION_MESSAGE);
tableQuery = new TableQueryFrame(tableName,dbUtils);
desktop.add(tableQuery);
tableQuery.setVisible(true);
}
private String[] parseKeyValueString(String kvString){
String[] kvPair = null;
int equals = kvString.indexOf("=");
if(equals>0){
kvPair = new String[2];
kvPair[0] = kvString.substring(0,equals).trim();
kvPair[1] = kvString.substring(equals+1).trim();
}
return kvPair;
}
private void selectDatabase(){
database = JOptionPane.showInputDialog(this,"Database:",
"Select database",JOptionPane.QUESTION_MESSAGE);
dbUtils = new DatabaseUtilities();
dbUtils.setDatabaseName(database);
dbUtils.setExceptionListener(new ExceptionListener());
tableMenu.enableMenuItem("New Table",true);
tableMenu.enableMenuItem("Drop Table",true);
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Chapter 7:Retrieving Data with SQL Queries
-254 -
editMenu.enableMenuItem("Insert",true);
editMenu.enableMenuItem("Update",true);
editMenu.enableMenuItem("Delete",true);
viewMenu.enableMenuItem("ResultSet",true);
}
private void executeSQLCommand(String SQLCommand){
dbUtils.execute(SQLCommand);
}
private void dropTable(){
tableName = JOptionPane.showInputDialog(this,"Table:",
"Select table",JOptionPane.QUESTION_MESSAGE);
int option = JOptionPane.showConfirmDialog(null,
"Dropping table "+tableName,
"Database "+database,
JOptionPane.OK_CANCEL_OPTION);
if(option==0){
executeSQLCommand("DROP TABLE "+tableName);
}
}
class MenuListener implements ActionListener{
public void actionPerformed(ActionEvent event){
String menuSelection = event.getActionCommand();
if(menuSelection.equals("Database")){
selectDatabase();
}else if(menuSelection.equals("New Table")){
displayTableBuilderFrame();
}else if(menuSelection.equals("Drop Table")){
dropTable();
}else if(menuSelection.equals("Insert")){
displayTableEditFrame();
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Chapter 7:Retrieving Data with SQL Queries
-255-
}else if(menuSelection.equals("ResultSet")){ // added for Chapter 7
displayTableQueryFrame();
}else if(menuSelection.equals("Exit")){
System.exit(0);
}
}
}
class ExceptionListener implements ActionListener{
public void actionPerformed(ActionEvent event){
String exception = event.getActionCommand();
JOptionPane.showMessageDialog(null, exception,
"SQL Error", JOptionPane.ERROR_MESSAGE);
}
}
class CommandListener implements ActionListener{
public void actionPerformed(ActionEvent event){
String SQLCommand = event.getActionCommand();
executeSQLCommand(SQLCommand);
}
}
public static void main(String args[]){
DBManager dbm = new DBManager();
}
}
It now remains to add the necessary JDBC code to run the query, as discussed in the next section.
JDBC Code
In the extended version of the DatabaseUtilities class in Listing 7-5, the method
executeQuery(String SQLQuery) has been added to return a Vector of Vectors containing the
row data from the table. The choice of a Vector of Vectors is driven partly by the inherent flexibility it
offers, and partly to demonstrate an approach that differs slightly from Listing 7-1. The method
getColumnNamesUsingQuery(String SQLCommand) has also been added. This method returns a
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Chapter 7:Retrieving Data with SQL Queries
-256 -
String array of column names pertinent to the query, rather than all the column names for the entire
table.
Listing 7-5: DatabaseUtilities
package jdbc_bible.part2;
import java.awt.event.*;
import java.sql.*;
import java.util.Vector;
import sun.jdbc.odbc.JdbcOdbcDriver;
public class DatabaseUtilities{
static String jdbcDriver = "sun.jdbc.odbc.JdbcOdbcDriver";
static String dbName = "Contacts";
static String urlRoot = "jdbc:odbc:";
private ActionListener exceptionListener = null;
public DatabaseUtilities(){
registerDriver();
}
public void setDatabaseName(String dbName){
this.dbName=dbName;
}
public void registerDriver(){
try {
Class.forName(jdbcDriver);
DriverManager.registerDriver(new JdbcOdbcDriver());
}
catch(ClassNotFoundException e){
reportException(e.getMessage());
}
catch(SQLException e){
reportException(e.getMessage());
}
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Chapter 7:Retrieving Data with SQL Queries
-257-
}
public void execute(String SQLCommand){
String url = urlRoot+dbName;
try {
Connection con = DriverManager.getConnection(url);
Statement stmt = con.createStatement();
stmt.execute(SQLCommand);
con.close();
}
catch(SQLException e){
reportException(e.getMessage());
}
}
public void execute(String[] SQLCommand){
String url = urlRoot+dbName;
try {
Connection con = DriverManager.getConnection(url);
Statement stmt = con.createStatement();
for(int i=0;i<SQLCommand.length;i++){
stmt.execute(SQLCommand[i]);
}
con.close();
}
catch(SQLException e){
reportException(e.getMessage());
}
}
public String[] getColumnNames(String tableName){
Vector dataSet = new Vector();
String[] columnNames = null;
String url = urlRoot+dbName;
String SQLCommand = "SELECT * FROM "+tableName+";";
try {
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Chapter 7:Retrieving Data with SQL Queries
-258-
Connection con = DriverManager.getConnection(url);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(SQLCommand);
ResultSetMetaData md = rs.getMetaData();
columnNames = new String[md.getColumnCount()];
for(int i=0;i<columnNames.length;i++){
columnNames[i] = md.getColumnLabel(i+1);
}
con.close();
}
catch(SQLException e){
reportException(e.getMessage());
}
return columnNames;
}
public String[] getColumnNamesUsingQuery(String SQLCommand){
Vector dataSet = new Vector();
String[] columnNames = null;
String url = urlRoot+dbName;
try {
Connection con = DriverManager.getConnection(url);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(SQLCommand);
ResultSetMetaData md = rs.getMetaData();
columnNames = new String[md.getColumnCount()];
for(int i=0;i<columnNames.length;i++){
columnNames[i] = md.getColumnLabel(i+1);
}
con.close();
}
catch(SQLException e){
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
[...]... that the elapsed can be calculated By commenting out the CREATE INDEX and DROP INDEX lines, speed improvement can easily be calculated Listing 8-1: Creating and dropping indexes package java_ databases.ch04; import java. sql.*; public class PrintIndexedResultSet{ public static void main(String args[]){ String query = "SELECT STATE, COUNT(STATE) FROM MEMBER_PROFILES GROUP BY STATE"; PrintIndexedResultSet... System.out.print(rs.getString(i)+((i==nColumns)?"\n":"\t")); } } java. util.Date endTime = new java. util.Date(); long elapsedTime = endTime.getTime() - startTime.getTime(); System.out.println("Elapsed time: "+elapsedTime); stmt.executeUpdate("DROP INDEX MEMBER_PROFILES.STATE_INDEX"); } catch(ClassNotFoundException e){ e.printStackTrace(); } catch(SQLException e){ } } } AM FL Y e.printStackTrace(); The example in Listing 8-1 is run against a membership database. .. regular basis The database management system generally saves the view by associating the SELECT statement with the view name and executing it when you want to access the view Summary In this chapter, you learn to perform the following tasks: § Sorting the data you retrieve from a database § Grouping the results for analysis § Performing statistical analyses on the data you retrieve from a database § Create... and the use of the UNION operator Joining Tables Chapter 2 explained how an efficient and reliable database design frequently requires the information in a practical database will be distributed across several tables, each of which contains sets of logically related data A typical example might be a database containing these four tables: § Customers, containing customer number, name, shipping address,... discussed in Chapter 1, which provides a more theoretical overview of Relational Database Management Systems Types of Joins There are two major types of Joins: Inner Joins and Outer Joins The difference between these two types of Joins goes back to the basic Set Theory underlying relational databases You can imagine the keys of two database tables, A and B as intersecting sets, as shown in Figure 9-1 -273-... you have executed a SQL query and obtained a sorted, grouped set of data from the database, it is frequently very useful to be able to save the query for reuse One of the ways SQL lets you do this is by using Views Views A view is similar to a table, but rather than being created as a fundamental part of the underlying database, it is created from the results of a query In fact, you can think of a view... Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con = DriverManager.getConnection ("jdbc:odbc:Members"); Statement stmt = con.createStatement(); stmt.executeUpdate("CREATE INDEX STATE_INDEX ON MEMBER_PROFILES(STATE)"); java. util.Date startTime = new java. util.Date(); ResultSet rs = stmt.executeQuery(query); ResultSetMetaData md = rs.getMetaData(); int nColumns = md.getColumnCount(); for(int i=1;i . jdbc_bible.part2;
import java. awt.*;
import java. awt.event.*;
import java. util.Vector;
import javax.swing.*;
import javax.swing.event.*;
public.
}
private void selectDatabase(){
database = JOptionPane.showInputDialog(this," ;Database: ",
"Select database& quot;,JOptionPane.QUESTION_MESSAGE);