aspose file tools*
The moose likes Beginning Java and the fly likes JTable & JDBC Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "JTable & JDBC" Watch "JTable & JDBC" New topic
Author

JTable & JDBC

Dean Reedy
Ranch Hand

Joined: Sep 10, 2001
Posts: 89
Trying to write a simple problem, and having troubles getting the basics. I have read chapters describing how to dynamiclly create and update JTables using the TableModel, but I just don't get it yet.
I was wondering is there a simple example of the following which works in JDK 1.3 using MS Access and ODBC:
A Frame which includes a panel, with a JTextField for entering in an SQL statement, a JTable for displaying the results of the SQL query from the JTextField. Just need the dynamics of displaying the results.
I have found some examples, but couldn't get them to work. Thankyou very much for the time.
Michael Fitzmaurice
Ranch Hand

Joined: Aug 22, 2001
Posts: 168
Hi
This basic example comes direct from "Java How To Program - Third Edition" by Deitel & Deitel. It doesn't use the TableModel constructor for JTable, it uses the overloaded version which takes 2 Vectors as arguments. It is written to access a simple MS Access database called "books" using the JDBC-ODBC bridge. All you should need to do is to change the database/connection/table details, the logic should be the same. Instead of the hardcoded query, just make the getTable() method take a String param that you get from the user.
I would normally have e-mailed this to you rather than posting it here, but your e-mail address does not seem to be available.
<code>
<pre>
// Fig. 18.24: TableDisplay.java
// This program displays the contents of the Authors table
// in the Books database.
import java.sql.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class TableDisplay extends JFrame {
private Connection connection;
private JTable table;

public TableDisplay()
{
// The URL specifying the Books database to which
// this program connects using JDBC to connect to a
// Microsoft ODBC database.
String url = "jdbc dbc:Books";
String username = "anonymous";
String password = "guest";
// Load the driver to allow connection to the database
try {
Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver" );
connection = DriverManager.getConnection(
url, username, password );
}
catch ( ClassNotFoundException cnfex ) {
System.err.println(
"Failed to load JDBC/ODBC driver." );
cnfex.printStackTrace();
System.exit( 1 ); // terminate program
}
catch ( SQLException sqlex ) {
System.err.println( "Unable to connect" );
sqlex.printStackTrace();
}
getTable();
setSize( 450, 150 );
show();
}
private void getTable()
{
Statement statement;
ResultSet resultSet;

try {
String query = "SELECT * FROM Authors";
statement = connection.createStatement();
resultSet = statement.executeQuery( query );
displayResultSet( resultSet );
statement.close();
}
catch ( SQLException sqlex ) {
sqlex.printStackTrace();
}
}
private void displayResultSet( ResultSet rs )
throws SQLException
{
// position to first record
boolean moreRecords = rs.next();
// If there are no records, display a message
if ( ! moreRecords ) {
JOptionPane.showMessageDialog( this,
"ResultSet contained no records" );
setTitle( "No records to display" );
return;
}
setTitle( "Authors table from Books" );
Vector columnHeads = new Vector();
Vector rows = new Vector();
try {
// get column heads
ResultSetMetaData rsmd = rs.getMetaData();

for ( int i = 1; i <= rsmd.getColumnCount(); ++i )
columnHeads.addElement( rsmd.getColumnName( i ) );
// get row data
do {
rows.addElement( getNextRow( rs, rsmd ) );
} while ( rs.next() );
// display table with ResultSet contents
table = new JTable( rows, columnHeads );
JScrollPane scroller = new JScrollPane( table );
getContentPane().add(
scroller, BorderLayout.CENTER );
validate();
}
catch ( SQLException sqlex ) {
sqlex.printStackTrace();
}
}
private Vector getNextRow( ResultSet rs,
ResultSetMetaData rsmd )
throws SQLException
{
Vector currentRow = new Vector();

for ( int i = 1; i <= rsmd.getColumnCount(); ++i )
switch( rsmd.getColumnType( i ) ) {
case Types.VARCHAR:
currentRow.addElement( rs.getString( i ) );
break;
case Types.INTEGER:
currentRow.addElement(
new Long( rs.getLong( i ) ) );
break;
default:
System.out.println( "Type was: " +
rsmd.getColumnTypeName( i ) );
}

return currentRow;
}
public void shutDown()
{
try {
connection.close();
}
catch ( SQLException sqlex ) {
System.err.println( "Unable to disconnect" );
sqlex.printStackTrace();
}
}
public static void main( String args[] )
{
final TableDisplay app = new TableDisplay();
app.addWindowListener(
new WindowAdapter() {
public void windowClosing( WindowEvent e )
{
app.shutDown();
System.exit( 0 );
}
}
);
}
}
</pre>
</code>
Hope this helps
Michael
------------------
"One good thing about music - when it hits, you feel no pain"
Bob Marley
[This message has been edited by Michael Fitzmaurice (edited September 17, 2001).]


"One good thing about music - when it hits, you feel no pain" <P>Bob Marley
Dean Reedy
Ranch Hand

Joined: Sep 10, 2001
Posts: 89
Good answers I got that to work. But the problem now is that I want to have a JTextField and a JButton, when I push the JButton the query from the JTextField is executed and displayed in the JTable. The example above I have got to work, but it is a one time deal. Any ideas, anyone.
Michael Fitzmaurice
Ranch Hand

Joined: Aug 22, 2001
Posts: 168
As I said, modify the getTable() method to take a String as a parameter. This String will be a SQL query typed by the user into your JTextArea. Remove the call to getTable() from within the constructor.
When the user clicks the JButton, use normal event handling to collect the String (query) from the JTextArea, and invoke your new <code>getTable(String query)</code> method.
The meat of the code I posted previously will do most of what you need, it needs only a couple of trivial changes to do what you want.
If you are unsure how to collect & handle the user input via the JTextArea and JButton, have a look at:
http://java.sun.com/docs/books/tutorial/uiswing/mini/index.html
http://java.sun.com/docs/books/tutorial/uiswing/index.html
Good luck
Michael
------------------
"One good thing about music - when it hits, you feel no pain"
Bob Marley
Dean Reedy
Ranch Hand

Joined: Sep 10, 2001
Posts: 89
Michael Thanks again.
I guess I should restate what I mean. I understand the textfield and the button. My problem is the dynamically creating the new JTable every time with a new query. Do I have to erase and recreate the table or can I remove everything from the table and repopulate? How can I delete all of the elements and repopulate the cells. It's the table I have problems with. If you think I should make another question for this answer I will do so. I want to thank you though for all of your help.
Dean
Dean Reedy
Ranch Hand

Joined: Sep 10, 2001
Posts: 89
Thanks for your help!
I found something on Sun's site of almost exactly what I am looking for. It dynamicly queries a database. I'll attached the url for anyone else Looking for an example like this: http://developer.java.sun.com/developer/Books/swing2/chapter18-05.html
and download the page at the bottom and this gives you the rwuired source-code. Note: in the directory "6" is the code I think is the best.
Thanks again
Dean
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: JTable & JDBC