Solved

JDBC and JTable

Posted on 2001-07-17
8
7,693 Views
Last Modified: 2013-11-23
I am trying to connect to a DB2 on an AS400. I thikn I have that part done, but I am also trying to display the results of the query in a table using the ResultSet method. I keep getting an error saying "Can not Resolve Symbol" on this line pointing to "new":

JTable table = new JTable(rs);

Here is the code I am using:

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.table.*;
import java.sql.*;
import java.applet.Applet;


public class CartonResearchDev extends JFrame{

     //Define the application contents
     Container contentPane;
     JTextField txtDate1;
     JTextField txtDate2;
     JLabel lblDate1;
     JLabel lblDate2;
     JButton btn1;
     JTable table;
     ResultSet rs;
     
     public void ExecuteSQL(){
     

     }          

     public CartonResearchDev(String args[]){

          //Main title of application
          super("Carton Research");

          //Define connection variables
          String user = "uk0dih3";
          String password = "erin1030";
          String url = "jdbc:odbc:pkms feed";
          String driver = "sun.jdbc.odbc.JdbcOdbcDriver";

          //Create the contents of the app
          this.setResizable(false);
          this.setDefaultCloseOperation(EXIT_ON_CLOSE);
          contentPane = getContentPane();
          contentPane.setLayout(new FlowLayout());
          lblDate1 = new JLabel("Enter First Date:");
          lblDate2= new JLabel("Enter Second Date:");
          txtDate1 = new JTextField(10);
          txtDate2 = new JTextField(10);
          contentPane.add(lblDate1);
          contentPane.add(txtDate1);
          contentPane.add(lblDate2);
          contentPane.add(txtDate2);
          btn1 = new JButton("Click Me To Run Query");
          //btn1.setMnemonic(KeyEvent.VK_C);
          btn1.addActionListener(new ActionListener(){
               public void actionPerformed (ActionEvent ae){}
          });

          contentPane.add(btn1);

          try{
     
               //Make connection to pkms history
               Class.forName(driver);
               Connection con = DriverManager.getConnection(url, user, password);
               Statement stmt = con.createStatement();

               //query to be run against pkms
               ResultSet rs = stmt.executeQuery("SELECT * FROM O3OHST00 WHERE O3STOR='25000'");
               
               //Create table for query results to be displayed
               JTable table = new JTable(rs);
               table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
               JScrollPane resultsPane = new JScrollPane(table);
               contentPane.add(resultsPane, BorderLayout.CENTER);
     
          //Catch errors in the connection          
          }catch(ClassNotFoundException cnfe){
               System.err.println(cnfe);
          }catch(SQLException sqle){
               System.err.println(sqle);
          }
          pack();
          setVisible(true);
         
     }

     public static void main(String args[]){


          //Create the Application window
          CartonResearchDev cr = new CartonResearchDev(args);
          cr.setSize(500, 500);
          cr.setVisible(true);

     }

}


Eventually this app will be able to query based off of user input into textfields, but that should be the simple problem. As for now, I can not even get it to display a standard query in the table, much less find out if my connection string is working.

Any help is appreciated.
berg
0
Comment
Question by:berg1375
  • 4
  • 2
  • 2
8 Comments
 
LVL 1

Expert Comment

by:yaseransari
ID: 6290104
Hello berg
            The JTable constructor  doesnt accept a result set object. What you have to do is to create a 2 dimensional array of rowdata out of the result set you get , and a single dimensional array of column names and pass it to JTable. This would solve your problem.
 
JTable(Object[][] rowData, Object[] columnNames)
          Constructs a JTable to display the values in the two dimensional array rowData, with column names columnNames.


Regards
Yaser Ansari
0
 
LVL 4

Author Comment

by:berg1375
ID: 6290173
Okay, I understand the concept you speak of, but can you elaborate a little more on the constructor? I am fairly new to Java, and do not understand constructors well at all.

thanks
berg
0
 
LVL 4

Author Comment

by:berg1375
ID: 6290294
Also, are you sure that arrays are the only way to go about this? I have a demo that uses a JTable on a JDBC connection, and it does not use arrays to populate the table. Like I said, I am fairly new to Java and JDBC, so please explain as well as you can.

Thanks
berg
0
 
LVL 1

Expert Comment

by:yaseransari
ID: 6290431
Hello berg,
           Constructors of a class are entities which intialize or create an object of a class.
In the case of JTable() it is necessary that the JTable get the data it requires to initialise itself and to diplay the data in row col fashion.
So we have to pass it a two dimensional array of Object which would contain the data to be displayed and also a one dimensional array of column names. This is all that is required for the JTable and passing these parameters to the constructor would ensure that the JTable initializes itself.

Now there are many ways in which you can initialise a JTable .
Instead of array you can use Vector as in

JTable(Vector rowData, Vector columnNames)
          Constructs a JTable to display the values in the Vector of Vectors rowData  with column names Vector  columnNames.

This constructor takes a vector instead of arrays as vector is library you can use conveniently instead of array.
In addition to this you also have other constructors.

JTable(TableModel dm)
          Constructs a JTable that is initialized with dm as the data model, a default column model, and a default selection model.

Now a TableModel is basciallly a holder of Data. As u must be knowing Swing components are designed using  the Model, View , controller architecture .
This means that the Model will hold the data required to be diplayed.
The controller handles the User genereated events such as changing the value of a particular col, and the View is what you see on the Screen .
Thus to intialise a JTable you can also pass a model object which holds the data and the Jtable then makes use of this Model to intiialise itslef.

For a detailed description on all constructors and how a Jtable works , visit the following link
http://www.dfki.uni-kl.de/km/java/java/tutorial/swing2/exercises/JTable/help.html

Hope this helps

Regards
Yaser Ansari


0
Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

 
LVL 1

Accepted Solution

by:
ny971181 earned 50 total points
ID: 6290812
berg,

try this: it works for me.
Note: I added a ResultsModel class in your class, just copy and paste and whole code in, you will be fine. and make sure you study it and understand it. good luck.

import java.sql.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;
import javax.swing.tree.*;
import javax.swing.border.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Vector;
import java.applet.Applet;

public class CartonResearchDev extends JFrame{

    //Define the application contents
    Container contentPane;
    JTextField txtDate1;
    JTextField txtDate2;
    JLabel lblDate1;
    JLabel lblDate2;
    JButton btn1;
    JTable table;
    ResultsModel model;
    ResultSet rs;
   
    public void ExecuteSQL(){
   

    }          

    public CartonResearchDev(String args[]){

         //Main title of application
         super("Carton Research");

         //Define connection variables
         String user = "sa";
         String password = "";
         String url = "jdbc:odbc:Northwind";
         String driver = "sun.jdbc.odbc.JdbcOdbcDriver";

         //Create the contents of the app
         this.setResizable(false);
         this.setDefaultCloseOperation(EXIT_ON_CLOSE);
         contentPane = getContentPane();
         contentPane.setLayout(new FlowLayout());
         lblDate1 = new JLabel("Enter First Date:");
         lblDate2= new JLabel("Enter Second Date:");
         txtDate1 = new JTextField(10);
         txtDate2 = new JTextField(10);
         contentPane.add(lblDate1);
         contentPane.add(txtDate1);
         contentPane.add(lblDate2);
         contentPane.add(txtDate2);
         btn1 = new JButton("Click Me To Run Query");
         //btn1.setMnemonic(KeyEvent.VK_C);
         btn1.addActionListener(new ActionListener(){
              public void actionPerformed (ActionEvent ae){}
         });

         contentPane.add(btn1);

         try{
   
              //Make connection to pkms history
              Class.forName(driver);
              Connection con = DriverManager.getConnection(url, user, password);
              Statement stmt = con.createStatement();

              //query to be run against pkms
              ResultSet rs = stmt.executeQuery("SELECT * FROM O3OHST00 WHERE O3STOR='25000'");
             
              model = new ResultsModel();
              model.setResultSet(rs);
              //Create table for query results to be displayed
              JTable table = new JTable(model);
              table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
              JScrollPane resultsPane = new JScrollPane(table);
              contentPane.add(resultsPane, BorderLayout.CENTER);
   
         //Catch errors in the connection          
         }catch(ClassNotFoundException cnfe){
              System.err.println(cnfe);
         }catch(SQLException sqle){
              System.err.println(sqle);
         }
         pack();
         setVisible(true);
         
    }

    public static void main(String args[]){


         //Create the Application window
         CartonResearchDev cr = new CartonResearchDev(args);
         cr.setSize(500, 500);
         cr.setVisible(true);

    }

}

class ResultsModel extends AbstractTableModel
{

  String[] columnNames = new String[0];
  Vector dataRows;              // Empty vector of rows

 
  public void setResultSet(ResultSet results)
  {

    if(results == null)
    {
      columnNames = new String[0];        // Reset the columns names
      dataRows.clear();                   // Remove all entries in the Vector
      fireTableChanged(null);             // Tell the table there is new model data
      return;
    }

    try
    {
      ResultSetMetaData metadata = results.getMetaData();

      int columns =  metadata.getColumnCount();    // Get number of columns
      columnNames = new String[columns];           // Array to hold names
     
      // Get the column names
      for(int i = 0; i < columns; i++)
        columnNames[i] = metadata.getColumnLabel(i+1);


      // Get all rows.
      dataRows = new Vector();                     // New Vector to store the data
      String[] rowData;                            // Stores one row
      while(results.next())                        // For each row...
      {
        rowData = new String[columns];             // create array to hold the data
        for(int i = 0; i < columns; i++)           // For each column
           rowData[i] = results.getString(i+1);    // retrieve the data item

        dataRows.addElement(rowData);              // Store the row in the vector
      }

      fireTableChanged(null);           // Signal the table there is new model data
    }
    catch (SQLException sqle)
    {
      System.err.println("Errors in setResultSet(): " + sqle);
    }

  }

  public int getColumnCount()
  {
    return columnNames.length;
  }

  public int getRowCount()
  {
    if(dataRows == null)
      return 0;
    else
      return dataRows.size();
  }

  public Object getValueAt(int row, int column)
  {
    return ((String[])(dataRows.elementAt(row)))[column];
  }

  public String getColumnName(int column)
  {
    return columnNames[column] == null ? "No Name" : columnNames[column];
  }

 
}                        
                        
0
 
LVL 1

Expert Comment

by:ny971181
ID: 6290826
oh, one more thing, you don't really need to import the java.applet.Applet class cause you don't use Applet anyways.

AND.. using Swing in Applet is pain in the toe! don't bother, you can still develop, but my point is it is gonna be many many hours for you to do it.
0
 
LVL 4

Author Comment

by:berg1375
ID: 6290859
That is great. It compiles now, abut give me a data source name not found error when I try to run it. I am using a DSN we use to access the DB2 with MSAccess. Will I need to create a new DSN for this?
0
 
LVL 4

Author Comment

by:berg1375
ID: 6290886
Never mind. I did not know that you had changed the DSN and URL. It works great. Now I will try to decipher the code.
0

Featured Post

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:
The viewer will learn how to use and create keystrokes in Netbeans IDE 8.0 for Windows.

757 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now