Hello members!

Could someone please give me a hand on this?
I have a JTable in my program that display query resuslt when the user search for a patient by entering the surname, the result is supposed to display in JTable in another frame.
Here is what I've done

import java.awt.BorderLayout;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Vector;
 
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
 
 
public class QueryTable extends JFrame
{
    /**
	 * 
	 */
	private static final long serialVersionUID = -4890348590846602933L;

	public QueryTable() throws ClassNotFoundException, SQLException
    {
        Vector<String> columnNames = new Vector<String>();
        Vector<Vector<Object>> data = new Vector<Vector<Object>>();
       Connection connection = null;
       Statement stmt = null;
       ResultSet rs = null;
 
        try
        {
            //  Connect to the Database (here: Oracle)
 
            String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
 
            String url = "JDBC:ODBC:Student";
            String userid = "";
            String password = "";
 
            Class.forName( driver );
            connection = DriverManager.getConnection( url, userid, password );
 
            //  Read data from a table
 
            
            stmt = connection.createStatement();
            rs = stmt.executeQuery(PatientReg.query);
            ResultSetMetaData md = rs.getMetaData();
            int columns = md.getColumnCount();
 
            //  Get column names
 
            for (int i = 1; i <= columns; i++)
            {
                columnNames.addElement( md.getColumnName(i) );
            }
 
            //  Get row data
 
            while (rs.next())
            {
                Vector<Object> row = new Vector<Object>(columns);
 
                for (int i = 1; i <= columns; i++)
                {
                    row.addElement( rs.getObject(i) );
                }
 
                data.addElement( row );
            }
        }
        catch(Exception e)
        {
            System.err.println( e );
        }
        finally{
          if(connection != null) connection.close();
          if(stmt !=null) stmt.close();
        }
 
        //  Create table with database data
 
        JTable table = new JTable(data, columnNames);
        
        JScrollPane scrollPane = new JScrollPane( table );
        getContentPane().add( scrollPane );
        
        JPanel buttonPanel = new JPanel();
        getContentPane().add( buttonPanel, BorderLayout.SOUTH );
    }
}

This is called in the search button's actionPerformed method

//Do search button
    Searchbtn = new JButton("Search");
    Searchbtn.addActionListener(new ActionListener(){
        public  void actionPerformed(ActionEvent e){

          try {
               QueryTable frame = new QueryTable();            
               frame.pack();
               frame.setSize(900, 500);
               frame.setLocationRelativeTo(null);
               frame.setVisible(true);
        } catch (SQLException ex) {
                ex.printStackTrace();
        }catch (ClassNotFoundException ex) {
                ex.printStackTrace();
        }
        
    }
        
  });

the problem is it only shows the column names but no records. though the table in the database contains records.

Thanks for helping!

Try to add some System.out.println in order to see if the data have been read:

JTable table = new JTable(data, columnNames);
// use for loops and print the data the the varaibles: "data", "columnNames" have

Also try this:

JTable table = new JTable(data, columnNames);

JScrollPane scrollPane = new JScrollPane( table );

JPanel panel = new JPanel();
panel.add(scrollPane);

getContentPane().add(panel);

Hello there!
I tried doing this

JTable table = new JTable(data, columnNames);
// use for loops and print the data the the varaibles: "data", "columnNames" have

It shows that the data is read from the database
Also tried this:

JTable table = new JTable(data, columnNames);

JScrollPane scrollPane = new JScrollPane( table );

JPanel panel = new JPanel();
panel.add(scrollPane);

getContentPane().add(panel);

But it gives still only the column names and no data in the table
Please help here is the code I've come up with.

import java.sql.*;
import java.util.*;
import javax.swing.*;

 
public class QueryTable extends JFrame
{
     String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
     String url = "JDBC:ODBC:Student";
     String userid = "";
     String password = "";
     ResultSet rs = null;
    public QueryTable(){

        Vector columnNames = new Vector();
        Vector data = new Vector();
            try{
          //  Connect to the Database
            Class.forName(driver);
            Connection connection = DriverManager.getConnection( url, userid, password );
 
            //  Read data from a table
            Statement stmt = connection.createStatement();
            try{
            rs = stmt.executeQuery( PatientReg.query );
            System.err.println("Data Retrieved from the table");
            }
            catch(Exception e){
            System.err.println("Exception" + e.getMessage());
            }
            ResultSetMetaData md = rs.getMetaData();
            int columns = md.getColumnCount();

            //  Get column names
            for (int i = 1; i <= columns; i++){
                columnNames.addElement( md.getColumnName(i) );
            }
 
            //  Get row data
            while ((rs!= null)&&(rs.next())){
                Vector row = new Vector(columns);
 
                for (int i = 1; i <= columns; i++)
                {
                    row.addElement( rs.getObject(i) );
                }
                data.addElement( row );
            }
            rs.close();
            stmt.close();
            }catch(Exception e){
            System.out.println( e );
           }
        
        //  Create table with database data
        JTable table = new JTable(data, columnNames);
 
        JScrollPane scrollPane = new JScrollPane( table );
        JPanel tabPan = new JPanel();
        tabPan.add(scrollPane);
        getContentPane().add(tabPan);
    }
}

This class is called in the search button's actionPerformed method

//Do search button
    Searchbtn = new JButton("Search");
    Searchbtn.addActionListener(new ActionListener(){

        public void actionPerformed(ActionEvent e){
        try{
            QueryTable qtable = new QueryTable();
            qtable.setSize(700,500);
            qtable.setVisible(true);
        }catch(Exception cnfe){
            cnfe.printStackTrace();   
         }
       }
    });

Thanks for the support!

I wouldn't have done it that way, so I don't know how your code will behave exactly.
So the only thing I can think of is for you to change the:

row.addElement( rs.getObject(i) )

TO:

row.addElement( rs.getString(i) )

Also you are not closing the Connection object, unless I missed that.

Also this call: rs = stmt.executeQuery( PatientReg.query )
Never returns null ResultSet.
So you can have your while to be:

while (rs.next()) {

}

I wouldn't have done it that way, so I don't know how your code will behave exactly.
So the only thing I can think of is for you to change the:

row.addElement( rs.getObject(i) )

TO:

row.addElement( rs.getString(i) )

Also you are not closing the Connection object, unless I missed that.

Also this call: rs = stmt.executeQuery( PatientReg.query )
Never returns null ResultSet.
So you can have your while to be:

while (rs.next()) {

}

I tried your suggestion and it still not giving the data.
It seems like it is not retrieving the value from the textfield, cause i printed the PatientReg.query and it gives this:

SELECT * FROM PatientTable WHERE Surname=''

PatientReg.query is :

String query = "SELECT * FROM PatientTable WHERE Surname='"+ jtffreeQuery.getText()+"'";

so if it gives that value it means it is not getting the text from the textfield. But how could we tackle that?
Thanks!

When the class is first "executed" the query variable has this value:

String query = "SELECT * FROM PatientTable WHERE Surname='"+ jtffreeQuery.getText()+"'";

The text, I assume is empty, so it like writting:

String query = "SELECT * FROM PatientTable WHERE Surname='' ";

h

But when you click the button, the value at the field has changed, but the value of the query hasn't. You don't change the value of the variable. It cannot change on its own when you change something.

It is better to do something like this:

QueryTable qtable = new QueryTable(jtffreeQuery.getText());
qtable.setSize(700,500);
qtable.setVisible(true);
public QueryTable(String input) {
  String query = "SELECT * FROM PatientTable WHERE Surname='"+ input+"'";

// continue with the rest of the code.
}

In that way, you keep the class parametrized.

PS: Don't forget to close the Connection

commented: Thanks JavaAddict! this has been very helpful. +1

I tried your suggestion and it still not giving the data.
It seems like it is not retrieving the value from the textfield, cause i printed the PatientReg.query and it gives this:

SELECT * FROM PatientTable WHERE Surname=''

PatientReg.query is :

String query = "SELECT * FROM PatientTable WHERE Surname='"+ jtffreeQuery.getText()+"'";

so if it gives that value it means it is not getting the text from the textfield. But how could we tackle that?
Thanks!

Hey thanks Javaaddict! but I did it .
The problem was because I declare the query in PatientReg and initialised as static, thus it was not going to give me anything cause the textfield is already empty. What I did was to declare it in the PatientReg as a global variable then initialise it in the search button's actionPerformed method, thus it gives the value thatis entered in the textfield
here is roughly what I mean.

public class PatientReg extends JFrame {
.
.
.
  static String query ;
.
.
;
//then initialsed it here
  public void actionPerformed(ActionEvent e){
        try{
            query = "SELECT * FROM PatientTable WHERE Surname='"+ jtffreeQuery.getText()+"'";
            QueryTable qtable = new QueryTable();
            qtable.setSize(700,500);
            qtable.setVisible(true);
        }catch(Exception cnfe){
            cnfe.printStackTrace();   
        }
       }
    });

Now it works !!!. Thanks JavaAddict I couldn't have done without your help.

When the class is first "executed" the query variable has this value:

String query = "SELECT * FROM PatientTable WHERE Surname='"+ jtffreeQuery.getText()+"'";

The text, I assume is empty, so it like writting:

String query = "SELECT * FROM PatientTable WHERE Surname='' ";

h

But when you click the button, the value at the field has changed, but the value of the query hasn't. You don't change the value of the variable. It cannot change on its own when you change something.

It is better to do something like this:

QueryTable qtable = new QueryTable(jtffreeQuery.getText());
qtable.setSize(700,500);
qtable.setVisible(true);
public QueryTable(String input) {
  String query = "SELECT * FROM PatientTable WHERE Surname='"+ input+"'";

// continue with the rest of the code.
}

In that way, you keep the class parametrized.

PS: Don't forget to close the Connection

Thanks JavaAddict! Either of the two ways can work.
I tried yours too, it working!!!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.