DBTablepublic class DBTable extends JFrame
Fields Summary |
---|
private String | driver | private String | dbURL | private String | loginName | private String | password | private JTextArea | query | private JButton | submit | private Connection | con | private Statement | stmt | JTable | table | JScrollPane | scroller |
Constructors Summary |
---|
public DBTable()
super( "JDBC + JTable" );
connect();
getContentPane().add( query, BorderLayout.NORTH );
getContentPane().add( submit, BorderLayout.SOUTH );
submit.addActionListener( new ActionListener() {
public void actionPerformed( ActionEvent e )
{ performQuery();
}
});
addWindowListener( new WindowAdapter() {
public void windowClosing( WindowEvent e )
{ System.exit(0);
}
});
pack();
setVisible(true);
|
Methods Summary |
---|
private void | connect()connect to database
try
{ Class.forName( driver );
con = DriverManager.getConnection( dbURL, loginName, password );
stmt = con.createStatement();
}
catch( ClassNotFoundException cnf )
{ cnf.printStackTrace();
System.exit(0);
}
catch( SQLException e )
{ while( e != null )
{ System.out.println( e );
e = e.getNextException();
}
System.exit(0);
}
| public static void | main(java.lang.String[] args) new DBTable();
| private void | performQuery()send contents of TextArea to database
ResultSet res = null;
try
{ res = stmt.executeQuery( query.getText() );
}
catch( SQLException e )
{ while( e != null )
{ System.out.println( e );
e = e.getNextException();
}
return;
}
Vector header = null;
Vector rows = null;
try
{ ResultSetMetaData rsmd = res.getMetaData();
int cols = rsmd.getColumnCount();
header = new Vector();
int col;
for( col = 1; col <= cols; col++ )
{ header.add( rsmd.getColumnLabel( col ) );
}
rows = new Vector();
while( res.next() == true )
{ Vector row = new Vector();
for( col=1; col <= cols; col++ )
{ row.add( res.getString( col ) );
}
rows.add( row );
}
}
catch( SQLException e )
{ while( e != null )
{ e.printStackTrace();
e = e.getNextException();
}
return;
}
if( scroller != null )
{ getContentPane().remove( scroller );
}
table = new JTable( rows, header );
scroller = new JScrollPane( table );
table.setPreferredScrollableViewportSize( new Dimension( 300, 200 ) );
getContentPane().add( scroller, BorderLayout.CENTER );
pack();
|
|