Hi everyone...

I just finished making a program for Video Rental in java..its not much..just retrieves the data from the DB and we can add or edit it...it works perfectly. But now, i want it to display the "Client Name" and "Client ID" field from my Client table and "movie Name" and "Movie ID" field from the Movies table in the database. I want it all to be displayed as a single table with 4 fields respectively but i can't see to do it. I know its a very basic thing but its not wrking fr me. I am attaching my whole program over here. Please look into it and see if any1 can help me out..I tried googling and den implementing various types of codes in it..but then if i alter my program, it gives an error. Any type of help will be appreciated.

Thanks

Dani AI

Generated

A working approach splits the problem into two simple steps: (1) get a single ResultSet that contains the four columns you want (use an appropriate JOIN or a DB view), and (2) populate a Swing TableModel from that ResultSet and refresh the model whenever the app changes the database. was right to ask for focused code — the key bits are the SQL that returns the four columns and a refresh routine that repopulates the TableModel off the EDT so the UI stays responsive. is also right: you must explicitly refresh the table after DB changes.

Example refresh pattern (run DB work off the UI thread, then set the JTable model on the EDT):

private void refreshTable() {
  SwingWorker<DefaultTableModel,Void> w = new SwingWorker<DefaultTableModel,Void>() {
    protected DefaultTableModel doInBackground() throws Exception {
      Vector<String> cols = new Vector<>(Arrays.asList("Client ID","Client Name","Movie ID","Movie Name"));
      Vector<Vector<Object>> rows = new Vector<>();
      String sql = "SELECT c.client_id, c.client_name, m.movie_id, m.movie_name "
                 + "FROM client c JOIN rental r ON r.client_id=c.client_id "
                 + "JOIN movies m ON m.movie_id=r.movie_id"; // adapt to your schema
      try (Connection conn = getConnection();
           PreparedStatement ps = conn.prepareStatement(sql);
           ResultSet rs = ps.executeQuery()) {
        while (rs.next()) {
          Vector<Object> row = new Vector<>();
          row.add(rs.getObject(1)); row.add(rs.getString(2));
          row.add(rs.getObject(3)); row.add(rs.getString(4));
          rows.add(row);
        }
      }
      return new DefaultTableModel(rows, cols);
    }
    protected void done() {
      try { table.setModel(get()); } catch (Exception ex) { ex.printStackTrace(); }
    }
  };
  w.execute();
}

Practical tips and gotchas:

  • Call this refresh after every insert/update/delete your app performs. If external programs also change the DB, either poll periodically (Swing Timer) or implement an external notification mechanism.
  • Use PreparedStatement and try-with-resources to avoid leaks. Check transaction/commit settings if changes aren’t visible.
  • If you update the existing model instead of replacing it, call fireTableDataChanged() or setDataVector(...) so the JTable repaints.
  • Verify the SQL in a DB client first to ensure the expected rows are returned.

Adapting these patterns will give a single JTable with the four columns and keep it in sync with the data your application writes.

Recommended Answers

All 3 Replies

well ... no one is going to download and check all your code, post the relevant code here and we might be able to check what's missing.
and no, posting your entire application is not necessary, just the relevant code/method

hmm ok thanks for clearing it up stultsuke...m actually a newbie in asking questions in forums and all so that is why i didnt know how to go about it....so i will rephrase my question again...this is the code of the file that retrieves the data from the database

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

/**
 * Performs the database access
 */
public class DatabaseAccess
{ 
  // DatabaseAccess ODBC
  // Driver JDBC/ODBC constant
  final static private String drv = "sun.jdbc.odbc.JdbcOdbcDriver"; // DB driver
  
  // Path(URL) DB constant
  final static private String URL = "jdbc:odbc:VideoRentalStore"; // DB alias
  
  public Connection connection; // DB connection object
  
  /**
   * + connect(): boolean --
   * Opens a database connection returning a boolean value that indicates whether
   *the connection was established or not.
   */
  public boolean connect()
  {
    boolean isConnected = true;
    
    try
    {
      Class.forName(drv);
      
      connection = DriverManager.getConnection(URL, "", ""); 
    }
    catch(java.lang.ClassNotFoundException er1)
    {
      System.out.println(er1.getMessage());
      
      isConnected = false;
    }
    catch(SQLException ex)
    {
      System.out.println(ex.getMessage());
      
      isConnected = false;
    }
    return isConnected;
  }

  /**
   * + disconnect() --
   *    * Terminates the database connection.
   */
  public void disconnect()
  {
    try
    {
      connection.close();
    }
    catch(SQLException ex)
    {
      System.out.println(ex.getMessage());
    }
  }

  /**
   * + checkExist(par1: String): int ---
   * Receives (in par1) a complement to form a Query 
   * [SELECT COUNT(*) FROM] of type [table WHERE condition] 
   * and returns the total of records found
   */
  public int checkExist(String queryComplement)
  {
    int value = 0;
    
    try
    {
      Statement stm = connection.createStatement();
      
      ResultSet rs = stm.executeQuery("select count(*) from " + queryComplement);
      
      rs.next();
      
      value = rs.getInt(1);
      
      rs.close();
      
      stm.close();
    }
    catch(SQLException ex)
    {
      System.out.println("Query problems: select count(*) from " + queryComplement);
    }
    
    return value;
  }     

  /**
   * + retFields(par1: String[], par2: String, par3: String) ---
   * Receives complements of a given query of type
   * SELECT [par2] FROM [par3] and returns the array defined (in par1)
   * the columns of a record from this query
   */
  public void retFields(String[] complements, String query1, String query2)
  {
    try
    {
      Statement stm = connection.createStatement();
      
      ResultSet rs = stm.executeQuery("select " + query1 + " from " + query2);
      
      if(rs.next())
      {
        for (int i = 0; i < complements.length; i++)
       {
          complements[i] = rs.getString(i + 1);
       }
      }
      
      rs.close();
      
      stm.close();
    }
    catch(SQLException ex)
      {
      System.out.println("Query problems: select " + query1 + " From " + query2);
    }
  }     

  /**
   * + executeSQL(par1: String): int ---
   * Receives a SQL query (in par1) that can be: 
   *   INSERT INTO table (cmp1, cmp2) VALUES (val1, val2)
   *   UPDATE table SET cmp1 = val1 WHERE condition
   *   DELETE FROM table WHERE condition
   * and returns an integer value with the total of rows affected
   */
  public int executeSQL(String query)
  {
    int value = 0;
    
    try
    {
      Statement stm = connection.createStatement();
      
      value = stm.executeUpdate(query);
      
      stm.close();
    }
    catch(SQLException ex)
    {
      System.out.println("Query problems " + query);
    }
    
    return value;
  }

  /**
   * + returnCode(par1: String): String ---
   * Returns a single code based on a query sent through par1
   */
  public String returnCode(String query)
  {
    String cmp = "";
    
    Statement stm;
    
    try
    {
      stm = connection.createStatement();
      
      ResultSet rs = stm.executeQuery("select " + query);
      
      if(rs.next())
      {
        cmp = rs.getString(1);
      }
    }
    catch(SQLException ex)
    {
      System.out.println("Query problems: select " + query);
    }
    
    return cmp;
  }

  /**
   * + loadList(par1: JList, par2, par3: String) ----
   * Loads an object of type JList (received in par1)
   * based on a complement of query of type
   * SELECT [par2] FROM [par3].
   */
  public void loadList(JList list, String query1, String query2)
  {
    try
    {
      Vector row = new Vector();
      
      Statement stm = connection.createStatement();
      
      ResultSet rs = stm.executeQuery("select " + query1 + " from " +  query2);

      while(rs.next())
      {
        row.addElement(rs.getString(1));
      }
      
      list.setListData(row); 
      
      rs.close();
      
      stm.close();
    }
    catch(SQLException ex)
    {
      System.out.println("Query problems: select " + query1 + " from " + query2);
    }
  }    

  /**
   * + loadComboBox(par1: JComboBox, par2, par3: String) ----
   * Loads an object of type JComboBox (passed by par1)
   * based on the complement of a given query of type
   * SELECT [par2] FROM [par3].
   */
  public void loadComboBox(JComboBox combo, String query1, String query2)
  {
    try
    {
      Statement stm = connection.createStatement();
      
      ResultSet rs = stm.executeQuery("select " + query1 + " from " + query2);

      combo.removeAllItems();
      
      while(rs.next())
      {
        combo.addItem(rs.getString(1));
      }
      
      rs.close();
      
      stm.close();
    }
    catch(SQLException ex)
    {
      System.out.println("Query problems: select " + query1 + " from " + query2);
    }
  }

}

now this code interacts with the data from the database and i want all the data to be displayed as a single table using JTable command but the problem is that since this is a program with dynamic data, the changes that i do to the DB using my application are not reflected into the table.

so can anyone please help me with accomplishing that..

any help would be greatly appreciated...

Thanks

The data base changes wont be reflected in the JTree u need to use some refresh methods to refresh the data .

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.