JTable and Database communication

Hi all,
I have two files excerpts from my Java application. I feel that in order for me to get understood so well, with regards to a problem that challenged me, I had to post these two files as you can see below. They are called ResultSetTableModel.java and DisplayQueryResults.java [which gets displayed in an internal frame].
I have this code from ResultSetTableModel
// ResultSetTableModel.java
// A TableModel that supplies ResultSet data to a JTable.
import java.sql.Connection;
import java.sql.Statement;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import javax.swing.table.AbstractTableModel;
// ResultSet rows and columns are counted from 1 and JTable
// rows and columns are counted from 0. When processing
// ResultSet rows or columns for use in a JTable, it is
// necessary to add 1 to the row or column number to manipulate
// the appropriate ResultSet column (i.e., JTable column 0 is
// ResultSet column 1 and JTable row 0 is ResultSet row 1).
public class ResultSetTableModel extends AbstractTableModel
   private Connection connection;
   private Statement statement;
   private ResultSet resultSet;
   private ResultSetMetaData metaData;
   private int numberOfRows;
   // keep track of database connection status
   private boolean connectedToDatabase = false;
   // constructor initializes resultSet and obtains its meta data object;
   // determines number of rows
   public ResultSetTableModel(String driver, String url,
      String username, String password, String query)
      throws SQLException, ClassNotFoundException {        
      // load database driver class
      Class.forName(driver);
      // connect to database
      connection = DriverManager.getConnection(url, username, password);
      // create Statement to query database
      statement = connection.createStatement(
         ResultSet.TYPE_SCROLL_INSENSITIVE,
         ResultSet.CONCUR_READ_ONLY);
      // update database connection status
      connectedToDatabase = true;
      // set query and execute it
      setQuery(query);
   } // end constructor ResultSetTableModel
   // get class that represents column type
   public Class getColumnClass(int column) throws IllegalStateException {
      // ensure database connection is available
      if (!connectedToDatabase)
         throw new IllegalStateException("Not Connected to Database");
      // determine Java class of column
      try {
         String className = metaData.getColumnClassName(column + 1);
         // return Class object that represents className
         return Class.forName(className);
      } // end try
      catch (Exception exception) {
         exception.printStackTrace();
      } // end catch
      //return Object.class; // if problems occur above, assume type Object
      return getValueAt(0, column).getClass(); // added January 25, 2008 in stead of the one above
   } // end method getColumnClass
   // get number of columns in ResultSet
   public int getColumnCount() throws IllegalStateException {  
      // ensure database connection is available
      if (!connectedToDatabase)
         throw new IllegalStateException("Not Connected to Database");
      // determine number of columns
      try  {
         return metaData.getColumnCount();
      } // end try
      catch (SQLException sqlException) {
         sqlException.printStackTrace();
      } // end catch
      return 0; // if problems occur above, return 0 for number of columns
   } // end method getColumnCount
   // get name of a particular column in ResultSet
   public String getColumnName(int column) throws IllegalStateException {   
      // ensure database connection is available
      if (!connectedToDatabase)
         throw new IllegalStateException("Not Connected to Database");
      // determine column name
      try {
         return metaData.getColumnName(column + 1); 
      } // end try
      catch (SQLException sqlException) {
         sqlException.printStackTrace();
      } // end catch
      return ""; // if problems, return empty string for column name
   } // end method getColumnName
   // return number of rows in ResultSet
   public int getRowCount() throws IllegalStateException {     
      // ensure database connection is available
      if (!connectedToDatabase)
         throw new IllegalStateException("Not Connected to Database");
      return numberOfRows;
   } // end method getRowCount
   // obtain value in particular row and column
   public Object getValueAt(int row, int column)
      throws IllegalStateException {
      // ensure database connection is available
      if (!connectedToDatabase)
         throw new IllegalStateException("Not Connected to Database");
      // obtain a value at specified ResultSet row and column
      try {
         resultSet.absolute(row + 1);
         return resultSet.getObject(column + 1);
      } // end try
      catch ( SQLException sqlException ) {
         sqlException.printStackTrace();
      } // end catch
      return ""; // if problems, return empty string object
   } // end method getValueAt
    * Don't need to implement this method unless your table's
    * editable.
  public boolean isCellEditable(int row, int column) { // Added on January 25, 2008 6:51 A.M.
     //Note that the data/cell address is constant,
     //no matter where the cell appears onscreen.
     if (column < 2) {
        return false;
     } else {
        return true;
   // set new database query string
   public void setQuery(String query)
      throws SQLException, IllegalStateException {
      // ensure database connection is available
      if (!connectedToDatabase)
         throw new IllegalStateException("Not Connected to Database");
      // specify query and execute it
      resultSet = statement.executeQuery(query);
      // obtain meta data for ResultSet
      metaData = resultSet.getMetaData();
      // determine number of rows in ResultSet
      resultSet.last();                   // move to last row
      numberOfRows = resultSet.getRow();  // get row number    
      // notify JTable that model has changed
      fireTableStructureChanged();
   } // end method setQuery
   // close Statement and Connection              
   public void disconnectFromDatabase() {             
      if (!connectedToDatabase)                 
         return;
      // close Statement and Connection           
      try {                                           
         statement.close();                       
         connection.close();                      
      } // end try                                
      catch (SQLException sqlException) {                                           
         sqlException.printStackTrace();          
      } // end catch                              
      finally { // update database connection status                                          
         connectedToDatabase = false;             
      } // end finally                            
   } // end method disconnectFromDatabase         
}  // end class ResultSetTableModelThe DisplayQueryResults code follows:
// DisplayQueryResults.java
// Display the contents of the Authors table in the
// Books database.
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.sql.SQLException;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;
import javax.swing.JTable;
import javax.swing.JOptionPane;
import javax.swing.JButton;
import javax.swing.Box;
import javax.swing.JInternalFrame;
import java.util.*; // for the Bundle
import javax.swing.event.InternalFrameEvent;
import javax.swing.event.InternalFrameListener;
import javax.swing.event.InternalFrameAdapter;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.*; // step 1
import javax.swing.table.TableModel; // step 1
public class DisplayQueryResults extends JInternalFrame implements TableModelListener { // step 2
   // JDBC driver, database URL, username and password
   ResourceBundle bundle = ResourceBundle.getBundle("Accounting");
   String JDBC_DRIVER = bundle.getString("Driver");
   String DATABASE_URL = bundle.getString("URL");
   String USERNAME = bundle.getString("User");
   String PASSWORD = bundle.getString("Password");
   String DEFAULT_QUERY = bundle.getString("Query");
   private ResultSetTableModel tableModel;
   private JTextArea queryArea;
   static final int xOffset = 0, yOffset = 200;
   // create ResultSetTableModel and GUI
   public DisplayQueryResults() {  
      super("Sales of the Day",
              true, //resizable
              true, //closable
              true, //maximizable
              false);//iconifiable
      //...Create the GUI and put it in the window...
      //Set the window's location.
      setLocation(xOffset, yOffset);
      // create ResultSetTableModel and display database table
      try {
         // create TableModel for results of query SELECT * FROM authors
         tableModel = new ResultSetTableModel(JDBC_DRIVER, DATABASE_URL,
            USERNAME, PASSWORD, DEFAULT_QUERY);
         // set up JTextArea in which user types queries
         queryArea = new JTextArea(DEFAULT_QUERY, 1, 100);
         queryArea.setWrapStyleWord(true);
         queryArea.setLineWrap(true);
         JScrollPane scrollPane = new JScrollPane(queryArea,
            ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
            ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
         // set up JButton for submitting queries
         JButton submitButton = new JButton("Submit Query");
         // create Box to manage placement of queryArea and
         // submitButton in GUI
         Box box = Box.createHorizontalBox();
         box.add(scrollPane);
         box.add(submitButton);
         // create JTable delegate for tableModel
         final JTable resultTable = new JTable(tableModel);
         resultTable.setFillsViewportHeight(true); // Makes the empty space heights white
         resultTable.setRowSelectionAllowed(true);
         resultTable.getModel().addTableModelListener(this); // step 3
         // place GUI components on content pane
         add(box, BorderLayout.NORTH);
         add(new JScrollPane(resultTable), BorderLayout.CENTER);
         // create event listener for submitButton
         submitButton.addActionListener(
            new ActionListener()
               // pass query to table model
               public void actionPerformed(ActionEvent event)
                  // perform a new query
                  try
                     tableModel.setQuery(queryArea.getText());
                  } // end try
                  catch ( SQLException sqlException)
                     JOptionPane.showMessageDialog(null,
                        sqlException.getMessage(), "Database error",
                        JOptionPane.ERROR_MESSAGE);
                     // try to recover from invalid user query
                     // by executing default query
                     try {
                        tableModel.setQuery(DEFAULT_QUERY);
                        queryArea.setText(DEFAULT_QUERY);
                     } // end try
                     catch (SQLException sqlException2) {
                        JOptionPane.showMessageDialog(null,
                           sqlException2.getMessage(), "Database error",
                           JOptionPane.ERROR_MESSAGE);
                        // ensure database connection is closed
                        tableModel.disconnectFromDatabase();
                        System.exit(1); // terminate application
                     } // end inner catch                  
                  } // end outer catch
               } // end actionPerformed
            }  // end ActionListener inner class         
         ); // end call to addActionListener
         //...Then set the window size or call pack...
            setSize(750,300);
         setVisible(true); // display window 
      } // end try
      catch (ClassNotFoundException classNotFound) {
         JOptionPane.showMessageDialog(null,
            "MySQL driver not found", "Driver not found",
            JOptionPane.ERROR_MESSAGE);
         System.exit(1); // terminate application
      } // end catch
      catch (SQLException sqlException) {
         JOptionPane.showMessageDialog(null, sqlException.getMessage(),
            "Database error", JOptionPane.ERROR_MESSAGE);
         // ensure database connection is closed
         tableModel.disconnectFromDatabase();
         System.exit(1);   // terminate application
      } // end catch
      // dispose of window when user quits application (this overrides
      // the default of HIDE_ON_CLOSE)
      setDefaultCloseOperation(DISPOSE_ON_CLOSE);
      // ensure database connection is closed when user quits application
      addInternalFrameListener(
         new InternalFrameAdapter() {
            // disconnect from database and exit when window has closed
            public void windowClosed(WindowEvent event) {
               tableModel.disconnectFromDatabase();
               System.exit(0);
            } // end method windowClosed
         } // end WindowAdapter inner class
      ); // end call to addWindowListener
   } // end DisplayQueryResults constructor
   public void tableChanged(TableModelEvent e) { // step 4
        int row = e.getFirstRow();
        int column = e.getColumn();
        TableModel model = (TableModel)e.getSource();
        String columnName = model.getColumnName(column);
        Object tableModel = model.getValueAt(row, column);
        // Do something with the data...
        System.out.println(tableModel);
        System.out.println("data");
   // execute application
   public static void main(String args[]) {
      new DisplayQueryResults();    
   } // end main
} // end class DisplayQueryResultsMy problem:
is in these lines:
public void tableChanged(TableModelEvent e) { // step 4
        int row = e.getFirstRow();
        int column = e.getColumn();
        TableModel model = (TableModel)e.getSource();
        String columnName = model.getColumnName(column);
        Object tableModel = model.getValueAt(row, column);
        // Do something with the data...
        System.out.println(tableModel);
        System.out.println("data"); // should output in the console
    }How do we notify java that a cell on a row has changed so that we can reflect the changes to the database. The current application shows that the data in cells are editable, but when we edit a cell and hit enter, data changes back to the previous data in that particular cell. And the data as well does not change its state: for example, if a data in the table has a value of boolean value false [checkbox unchecked], I can not modify the checkbox state to checked state. The tableChanged method does not get executed, and therefore, this is a serious error that I cant figure out.
My question:
What code should I write so that I will be able to notify java of the changed cell and how do we write the code that will reflect the changed values in a cell into the database?
Edited by: Oliverbob on Jan 26, 2008 9:54 PM

Why don't you check out the link shown below:
http://www.aokabc.com
and just follow the white rabbit!
;o)
V.V.

Similar Messages

  • Jtable and database

    hi,
    i am using jdevlopper 10g and oracle 10g express.
    i create a database and a new connection to it.
    in the first frame, i created a new jtable and i want that it containts data from the database.
    is any one can help me.
    thanks

    Hi,
    you have two options:
    - Use ADF and ADF Swing, in which cae the database connect is through a business service (e.g. ADF Business Components or EJB)
    - Create a JDBC connection to the database and populate the JTable model with the data (which is cumbersome). You find tutorials on the web of how to do this.
    Frank

  • Problem about jtable and database

    The problem is that when i clicked the button to save the values of textfields and text area, although the table is supposed to show the new list of datas from the db, it adds the new data list to the end of the first list. I have to list one old and one new in jtable.
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    * DatabaseConnection.java
    * Created on 28.Aðu.2008, 11:24:52
    package databaseconnection;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    import java.util.Vector;
    import javax.swing.table.AbstractTableModel;
    import javax.swing.table.TableModel;
    * @author ARAGORN
    public class DatabaseConnection extends javax.swing.JFrame {
        /** Creates new form DatabaseConnection */
        public DatabaseConnection() {
            try {
                Class.forName("com.mysql.jdbc.Driver");
                con = DriverManager.getConnection("jdbc:mysql://localhost:3306/Students", "admin", "1837837");
                st = con.createStatement();
            } catch (Exception e) {
                System.out.println("Database Connection Error!");
            try {
                ResultSet rs = st.executeQuery("SELECT*FROM studentdata");
                while (rs.next()) {
                    Object[] rowValues = {rs.getInt(1),rs.getString(2),rs.getString(3),rs.getInt(4),rs.getString(5),rs.getString(6),rs.getInt(7)};
                    row.addElement(rowValues);
                data = new Object[row.size()][7];
                for(int i=0;i<row.size();i++){
                    data=(Object[]) row.get(i);
    } catch (Exception e) {
    System.out.println("reading error!");
    initComponents();
    /** This method is called from within the constructor to
    * initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is
    * always regenerated by the Form Editor.
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {
    jScrollPane1 = new javax.swing.JScrollPane();
    jTable1 = new javax.swing.JTable();
    jPanel1 = new javax.swing.JPanel();
    jLabel1 = new javax.swing.JLabel();
    jTextField1 = new javax.swing.JTextField();
    jSeparator1 = new javax.swing.JSeparator();
    jLabel2 = new javax.swing.JLabel();
    jTextField2 = new javax.swing.JTextField();
    jLabel3 = new javax.swing.JLabel();
    jTextField3 = new javax.swing.JTextField();
    jTextField4 = new javax.swing.JTextField();
    jLabel4 = new javax.swing.JLabel();
    jScrollPane2 = new javax.swing.JScrollPane();
    jTextArea1 = new javax.swing.JTextArea();
    jLabel5 = new javax.swing.JLabel();
    jLabel6 = new javax.swing.JLabel();
    jTextField5 = new javax.swing.JTextField();
    jLabel7 = new javax.swing.JLabel();
    jTextField6 = new javax.swing.JTextField();
    jButton1 = new javax.swing.JButton();
    jButton2 = new javax.swing.JButton();
    jButton3 = new javax.swing.JButton();
    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    addWindowListener(new java.awt.event.WindowAdapter() {
    public void windowOpened(java.awt.event.WindowEvent evt) {
    formWindowOpened(evt);
    jTable1.setModel(new javax.swing.table.DefaultTableModel(data,heading)
    jScrollPane1.setViewportView(jTable1);
    jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Öðrenci Bilgileri", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 12))); // NOI18N
    jLabel1.setText("Öðrenci No : ");
    jLabel2.setText("Adý : ");
    jLabel3.setText("Sýnýf : ");
    jLabel4.setText("Soyad : ");
    jTextArea1.setColumns(20);
    jTextArea1.setRows(5);
    jScrollPane2.setViewportView(jTextArea1);
    jLabel5.setText("Adress : ");
    jLabel6.setText("Tel : ");
    jLabel7.setText("Þube : ");
    javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
    jPanel1.setLayout(jPanel1Layout);
    jPanel1Layout.setHorizontalGroup(
    jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(jPanel1Layout.createSequentialGroup()
    .addGap(22, 22, 22)
    .addComponent(jLabel1)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addContainerGap(364, Short.MAX_VALUE))
    .addComponent(jSeparator1, javax.swing.GroupLayout.DEFAULT_SIZE, 581, Short.MAX_VALUE)
    .addGroup(jPanel1Layout.createSequentialGroup()
    .addGap(40, 40, 40)
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
    .addComponent(jLabel6)
    .addComponent(jLabel2)
    .addComponent(jLabel4)
    .addComponent(jLabel5))
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(jPanel1Layout.createSequentialGroup()
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
    .addComponent(jTextField4)
    .addComponent(jTextField2, javax.swing.GroupLayout.DEFAULT_SIZE, 131, Short.MAX_VALUE))
    .addGap(28, 28, 28)
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
    .addComponent(jLabel3)
    .addComponent(jLabel7))
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addComponent(jTextField3, javax.swing.GroupLayout.DEFAULT_SIZE, 248, Short.MAX_VALUE)
    .addComponent(jTextField6, javax.swing.GroupLayout.DEFAULT_SIZE, 248, Short.MAX_VALUE)))
    .addComponent(jTextField5, javax.swing.GroupLayout.PREFERRED_SIZE, 132, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 320, javax.swing.GroupLayout.PREFERRED_SIZE))
    .addGap(49, 49, 49))
    jPanel1Layout.setVerticalGroup(
    jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(jPanel1Layout.createSequentialGroup()
    .addContainerGap()
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(jLabel1)
    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(jLabel2)
    .addComponent(jLabel3)
    .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(jLabel4)
    .addComponent(jLabel7)
    .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addComponent(jTextField6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addComponent(jLabel5)
    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(jLabel6)
    .addComponent(jTextField5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
    .addContainerGap())
    jButton1.setText("Kaydet");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jButton1ActionPerformed(evt);
    jButton2.setText("Temizle");
    jButton2.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jButton2ActionPerformed(evt);
    jButton3.setText("Çýk");
    jButton3.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jButton3ActionPerformed(evt);
    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addContainerGap()
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 597, Short.MAX_VALUE)
    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
    .addComponent(jButton1)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addComponent(jButton2)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addComponent(jButton3)))
    .addContainerGap())
    layout.setVerticalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addContainerGap()
    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    .addGap(18, 18, 18)
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(jButton1)
    .addComponent(jButton2)
    .addComponent(jButton3))
    .addGap(38, 38, 38))
    pack();
    }// </editor-fold>
    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                        
    System.exit(0);
    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                        
    jTextField1.setText("");
    jTextField2.setText("");
    jTextField3.setText("");
    jTextField4.setText("");
    jTextField5.setText("");
    jTextField6.setText("");
    jTextArea1.setText("");
    private void formWindowOpened(java.awt.event.WindowEvent evt) {                                 
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                        
    try {
    st.executeUpdate("INSERT studentdata(Ogrenci_no,Ad,Soyad,Sinif,Sube,Adres,Tel) VALUES(" +
    Integer.parseInt(jTextField1.getText()) + ", '" +
    jTextField2.getText() + "', '" +
    jTextField4.getText() + "', " +
    Integer.parseInt(jTextField3.getText()) + ", '" +
    jTextField6.getText() + "', '" +
    jTextArea1.getText() + "', " +
    Integer.parseInt(jTextField5.getText()) +
    } catch (SQLException e) {
    System.out.println("Writing data Error!");
    try {
    ResultSet rs = st.executeQuery("SELECT * FROM studentdata");
    while (rs.next()) {
    Object[] rowValues = {rs.getInt(1),rs.getString(2),rs.getString(3),rs.getInt(4),rs.getString(5),rs.getString(6),rs.getInt(7)};
    row.addElement(rowValues);
    data = new Object[row.size()][7];
    for(int i=0;i<row.size();i++){
    data[i]=(Object[]) row.get(i);
    } catch (Exception e) {
    System.out.println("reading error!");
    jTable1.setModel(new MyTableModel());
    jTable1.setVisible(true);
    * @param args the command line arguments
    public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
    new DatabaseConnection().setVisible(true);
    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JTextField jTextField3;
    private javax.swing.JTextField jTextField4;
    private javax.swing.JTextField jTextField5;
    private javax.swing.JTextField jTextField6;
    // End of variables declaration
    Connection con;
    Statement st;
    Vector row = new Vector();
    Object[][] data;
    Object[] heading = {"Öðrenci_No","Ad","Soyad","Sýnýf","Sube","Adres","Tel"};
    class MyTableModel extends AbstractTableModel{
    public int getColumnCount(){
    return heading.length;
    public int getRowCount(){
    return data.length;
    @Override
    public String getColumnName(int column){
    return heading[column].toString();
    public Object getValueAt(int row, int column){
    return data[row][column];
    public boolean isCellEditable(){
    return false;
    @Override
    public void setValueAt(Object value, int row, int column){
    data[row][column] = value;
    fireTableCellUpdated(row, column);
    }                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    

    any one to help ?

  • How to use JTable and database

    how i want to know how to store data into Jtable from the database for the end users.
    any tutorial or example will be helpfull.
    thank you

    my problem is i want to store data that i will get from the database into a JTableThen you problem is with Swing in which case you should be searching the Swing forum for answers. This question has been asked and answered several times. I know I've posted solutions before.

  • JTable and Database (mysql)

    Does anyone know or have codes on how to get value from JTable cells and it will store into database (mysql).

    You will have to extract the values for each column within the row and then construct an INSERT statement with the column names/values (or simply values if all columns)
    If the row already exists and you want to update it, you will have to write an UPDATE stmt.
    I don't have the code at hand, but will post it if I find it

  • JTable and Databases

    Hi all,
    I have two files excerpts from my Java application. I feel that in order for me to get understood so well, with regards to a problem that challenged me, I had to post these two files as you can see below. They are called ResultSetTableModel.java and DisplayQueryResults.java [which gets displayed in an internal frame].
    I have this code from ResultSetTableModel
    // ResultSetTableModel.java
    // A TableModel that supplies ResultSet data to a JTable.
    import java.sql.Connection;
    import java.sql.Statement;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.ResultSetMetaData;
    import java.sql.SQLException;
    import javax.swing.table.AbstractTableModel;
    // ResultSet rows and columns are counted from 1 and JTable
    // rows and columns are counted from 0. When processing
    // ResultSet rows or columns for use in a JTable, it is
    // necessary to add 1 to the row or column number to manipulate
    // the appropriate ResultSet column (i.e., JTable column 0 is
    // ResultSet column 1 and JTable row 0 is ResultSet row 1).
    public class ResultSetTableModel extends AbstractTableModel
       private Connection connection;
       private Statement statement;
       private ResultSet resultSet;
       private ResultSetMetaData metaData;
       private int numberOfRows;
       // keep track of database connection status
       private boolean connectedToDatabase = false;
       // constructor initializes resultSet and obtains its meta data object;
       // determines number of rows
       public ResultSetTableModel(String driver, String url,
          String username, String password, String query)
          throws SQLException, ClassNotFoundException {        
          // load database driver class
          Class.forName(driver);
          // connect to database
          connection = DriverManager.getConnection(url, username, password);
          // create Statement to query database
          statement = connection.createStatement(
             ResultSet.TYPE_SCROLL_INSENSITIVE,
             ResultSet.CONCUR_READ_ONLY);
          // update database connection status
          connectedToDatabase = true;
          // set query and execute it
          setQuery(query);
       } // end constructor ResultSetTableModel
       // get class that represents column type
       public Class getColumnClass(int column) throws IllegalStateException {
          // ensure database connection is available
          if (!connectedToDatabase)
             throw new IllegalStateException("Not Connected to Database");
          // determine Java class of column
          try {
             String className = metaData.getColumnClassName(column + 1);
             // return Class object that represents className
             return Class.forName(className);
          } // end try
          catch (Exception exception) {
             exception.printStackTrace();
          } // end catch
          //return Object.class; // if problems occur above, assume type Object
          return getValueAt(0, column).getClass(); // added January 25, 2008 in stead of the one above
       } // end method getColumnClass
       // get number of columns in ResultSet
       public int getColumnCount() throws IllegalStateException {  
          // ensure database connection is available
          if (!connectedToDatabase)
             throw new IllegalStateException("Not Connected to Database");
          // determine number of columns
          try  {
             return metaData.getColumnCount();
          } // end try
          catch (SQLException sqlException) {
             sqlException.printStackTrace();
          } // end catch
          return 0; // if problems occur above, return 0 for number of columns
       } // end method getColumnCount
       // get name of a particular column in ResultSet
       public String getColumnName(int column) throws IllegalStateException {   
          // ensure database connection is available
          if (!connectedToDatabase)
             throw new IllegalStateException("Not Connected to Database");
          // determine column name
          try {
             return metaData.getColumnName(column + 1); 
          } // end try
          catch (SQLException sqlException) {
             sqlException.printStackTrace();
          } // end catch
          return ""; // if problems, return empty string for column name
       } // end method getColumnName
       // return number of rows in ResultSet
       public int getRowCount() throws IllegalStateException {     
          // ensure database connection is available
          if (!connectedToDatabase)
             throw new IllegalStateException("Not Connected to Database");
          return numberOfRows;
       } // end method getRowCount
       // obtain value in particular row and column
       public Object getValueAt(int row, int column)
          throws IllegalStateException {
          // ensure database connection is available
          if (!connectedToDatabase)
             throw new IllegalStateException("Not Connected to Database");
          // obtain a value at specified ResultSet row and column
          try {
             resultSet.absolute(row + 1);
             return resultSet.getObject(column + 1);
          } // end try
          catch ( SQLException sqlException ) {
             sqlException.printStackTrace();
          } // end catch
          return ""; // if problems, return empty string object
       } // end method getValueAt
        * Don't need to implement this method unless your table's
        * editable.
      public boolean isCellEditable(int row, int column) { // Added on January 25, 2008 6:51 A.M.
         //Note that the data/cell address is constant,
         //no matter where the cell appears onscreen.
         if (column < 2) {
            return false;
         } else {
            return true;
       // set new database query string
       public void setQuery(String query)
          throws SQLException, IllegalStateException {
          // ensure database connection is available
          if (!connectedToDatabase)
             throw new IllegalStateException("Not Connected to Database");
          // specify query and execute it
          resultSet = statement.executeQuery(query);
          // obtain meta data for ResultSet
          metaData = resultSet.getMetaData();
          // determine number of rows in ResultSet
          resultSet.last();                   // move to last row
          numberOfRows = resultSet.getRow();  // get row number    
          // notify JTable that model has changed
          fireTableStructureChanged();
       } // end method setQuery
       // close Statement and Connection              
       public void disconnectFromDatabase() {             
          if (!connectedToDatabase)                 
             return;
          // close Statement and Connection           
          try {                                           
             statement.close();                       
             connection.close();                      
          } // end try                                
          catch (SQLException sqlException) {                                           
             sqlException.printStackTrace();          
          } // end catch                              
          finally { // update database connection status                                          
             connectedToDatabase = false;             
          } // end finally                            
       } // end method disconnectFromDatabase         
    }  // end class ResultSetTableModelThe DisplayQueryResults code follows:
    // DisplayQueryResults.java
    // Display the contents of the Authors table in the
    // Books database.
    import java.awt.BorderLayout;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.sql.SQLException;
    import javax.swing.JFrame;
    import javax.swing.JTextArea;
    import javax.swing.JScrollPane;
    import javax.swing.ScrollPaneConstants;
    import javax.swing.JTable;
    import javax.swing.JOptionPane;
    import javax.swing.JButton;
    import javax.swing.Box;
    import javax.swing.JInternalFrame;
    import java.util.*; // for the Bundle
    import javax.swing.event.InternalFrameEvent;
    import javax.swing.event.InternalFrameListener;
    import javax.swing.event.InternalFrameAdapter;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import javax.swing.ListSelectionModel;
    import javax.swing.event.ListSelectionEvent;
    import javax.swing.event.ListSelectionListener;
    import javax.swing.event.*; // step 1
    import javax.swing.table.TableModel; // step 1
    public class DisplayQueryResults extends JInternalFrame implements TableModelListener { // step 2
       // JDBC driver, database URL, username and password
       ResourceBundle bundle = ResourceBundle.getBundle("Accounting");
       String JDBC_DRIVER = bundle.getString("Driver");
       String DATABASE_URL = bundle.getString("URL");
       String USERNAME = bundle.getString("User");
       String PASSWORD = bundle.getString("Password");
       String DEFAULT_QUERY = bundle.getString("Query");
       private ResultSetTableModel tableModel;
       private JTextArea queryArea;
       static final int xOffset = 0, yOffset = 200;
       // create ResultSetTableModel and GUI
       public DisplayQueryResults() {  
          super("Sales of the Day",
                  true, //resizable
                  true, //closable
                  true, //maximizable
                  false);//iconifiable
          //...Create the GUI and put it in the window...
          //Set the window's location.
          setLocation(xOffset, yOffset);
          // create ResultSetTableModel and display database table
          try {
             // create TableModel for results of query SELECT * FROM authors
             tableModel = new ResultSetTableModel(JDBC_DRIVER, DATABASE_URL,
                USERNAME, PASSWORD, DEFAULT_QUERY);
             // set up JTextArea in which user types queries
             queryArea = new JTextArea(DEFAULT_QUERY, 1, 100);
             queryArea.setWrapStyleWord(true);
             queryArea.setLineWrap(true);
             JScrollPane scrollPane = new JScrollPane(queryArea,
                ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
                ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
             // set up JButton for submitting queries
             JButton submitButton = new JButton("Submit Query");
             // create Box to manage placement of queryArea and
             // submitButton in GUI
             Box box = Box.createHorizontalBox();
             box.add(scrollPane);
             box.add(submitButton);
             // create JTable delegate for tableModel
             final JTable resultTable = new JTable(tableModel);
             resultTable.setFillsViewportHeight(true); // Makes the empty space heights white
             resultTable.setRowSelectionAllowed(true);
             resultTable.getModel().addTableModelListener(this); // step 3
             // place GUI components on content pane
             add(box, BorderLayout.NORTH);
             add(new JScrollPane(resultTable), BorderLayout.CENTER);
             // create event listener for submitButton
             submitButton.addActionListener(
                new ActionListener()
                   // pass query to table model
                   public void actionPerformed(ActionEvent event)
                      // perform a new query
                      try
                         tableModel.setQuery(queryArea.getText());
                      } // end try
                      catch ( SQLException sqlException)
                         JOptionPane.showMessageDialog(null,
                            sqlException.getMessage(), "Database error",
                            JOptionPane.ERROR_MESSAGE);
                         // try to recover from invalid user query
                         // by executing default query
                         try {
                            tableModel.setQuery(DEFAULT_QUERY);
                            queryArea.setText(DEFAULT_QUERY);
                         } // end try
                         catch (SQLException sqlException2) {
                            JOptionPane.showMessageDialog(null,
                               sqlException2.getMessage(), "Database error",
                               JOptionPane.ERROR_MESSAGE);
                            // ensure database connection is closed
                            tableModel.disconnectFromDatabase();
                            System.exit(1); // terminate application
                         } // end inner catch                  
                      } // end outer catch
                   } // end actionPerformed
                }  // end ActionListener inner class         
             ); // end call to addActionListener
             //...Then set the window size or call pack...
                setSize(750,300);
             setVisible(true); // display window 
          } // end try
          catch (ClassNotFoundException classNotFound) {
             JOptionPane.showMessageDialog(null,
                "MySQL driver not found", "Driver not found",
                JOptionPane.ERROR_MESSAGE);
             System.exit(1); // terminate application
          } // end catch
          catch (SQLException sqlException) {
             JOptionPane.showMessageDialog(null, sqlException.getMessage(),
                "Database error", JOptionPane.ERROR_MESSAGE);
             // ensure database connection is closed
             tableModel.disconnectFromDatabase();
             System.exit(1);   // terminate application
          } // end catch
          // dispose of window when user quits application (this overrides
          // the default of HIDE_ON_CLOSE)
          setDefaultCloseOperation(DISPOSE_ON_CLOSE);
          // ensure database connection is closed when user quits application
          addInternalFrameListener(
             new InternalFrameAdapter() {
                // disconnect from database and exit when window has closed
                public void windowClosed(WindowEvent event) {
                   tableModel.disconnectFromDatabase();
                   System.exit(0);
                } // end method windowClosed
             } // end WindowAdapter inner class
          ); // end call to addWindowListener
       } // end DisplayQueryResults constructor
       public void tableChanged(TableModelEvent e) { // step 4
            int row = e.getFirstRow();
            int column = e.getColumn();
            TableModel model = (TableModel)e.getSource();
            String columnName = model.getColumnName(column);
            Object tableModel = model.getValueAt(row, column);
            // Do something with the data...
            System.out.println(tableModel);
            System.out.println("data");
       // execute application
       public static void main(String args[]) {
          new DisplayQueryResults();    
       } // end main
    } // end class DisplayQueryResultsMy problem:
    is in these lines:
    public void tableChanged(TableModelEvent e) { // step 4
            int row = e.getFirstRow();
            int column = e.getColumn();
            TableModel model = (TableModel)e.getSource();
            String columnName = model.getColumnName(column);
            Object tableModel = model.getValueAt(row, column);
            // Do something with the data...
            System.out.println(tableModel);
            System.out.println("data"); // should output in the console
        }How do we notify java that a cell on a row has changed so that we can reflect the changes to the database. The current application shows that the data in cells are editable, but when we edit a cell and hit enter, data changes back to the previous data in that particular cell. And the data as well does not change its state: for example, if a data in the table has a value of boolean value false [checkbox unchecked], I can not modify the checkbox state to checked state. The tableChanged method does not get executed, and therefore, this is a serious error that I cant figure out.
    My question:
    What code should I write so that I will be able to notify java of the changed cell and how do we write the code that will reflect the changed values in a cell into the database?
    Edited by: Oliverbob on Jan 26, 2008 8:40 PM

    This maybe what you're looking for??
    http://developer.java.sun.com/developer/Books/swing2/chapter18-09.html

  • Please help in storing JTable in database

    hai Abrami,
    I saw in JDK\bin\demo\jfc\Tableexample. but it contans example only for populating the Table with the values from database which I finished alraedy. But I treid of storing the Table values in database using VArray. but it contradicts with the several operations such as retireving Single field from database Updating the database when value single populated table changes.
    So please help me in this.This isthe final part of project.

    Bathina,
    Did you try doing an Internet search? I did one for the terms "jtable" and "database". Here are my results:
    http://tinyurl.com/4ttl4
    And if you just want someone to do your work for you, then try HotDispatch or Rent-A-Coder (or similar -- there are lots of others like these two).
    Good Luck,
    Avi.

  • How Can I use JTable Like Datagrid (Spreadsheet) and database

    Please how can I achieve the following in java:
    (1) Create a Grid (spreadsheets-Like) with JTable and be able to add new record (rows) as I reach the end of the last column during data entry.
    (2) Save the content of the grid to a text file as well as a database.
    (3) Retrieve the content of the text file or database to the Jtable
    (4) How can I connect to SQL Server without using JDBC-ODBC-bridge and also with Oracle.
    (5) How can I read and write to LPT and COMS ports

    If you don't know how to do any of this, you need to go through the tutorials. Start here: http://java.sun.com/docs/books/tutorial/
    James

  • How to put data in JTable from database

    hi everyone,
    i want to query the databse and put the result in the JTable and if possible i want to edit some information. For example: i have 5 records in the database query them and place them in JTable and each record has its own status. if i want to change the status For Example: the status of the 4 records are "Cleared" and the other one is "RELEASEd" so if i have JCombo Box to set the 4 records in to RELEASED status and then save the changes is that possible?
    thank you
    dhing

    In [url /thread.jsp?forum=54&thread=387565]this thread I describe how to use a result set as a basis for table data. Check some database tutorials for information on getting a result set.

  • JTable and ResultSet TableModel with big resultset

    Hi, I have a question about JTable and a ResultSet TableModel.
    I have to develop a swing JTable application that gets the data from a ResultSetTableModel where the user can update the jtable data.
    The problem is the following:
    the JTable have to contain the whole data of the source database table. Currently I have defined a
    a TYPE_SCROLL_SENSITIVE & CONCUR_UPDATABLE statement.
    The problem is that when I execute the query the whole ResultSet is "downloaded" on the client side application (my jtable) and I could receive (with big resultsets) an "out of memory error"...
    I have investigate about the possibility of load (in the client side) only a small subset of the resultset but with no luck. In the maling lists I see that the only way to load the resultset incrementally is to define a forward only resultset with autocommit off, and using setFetchSize(...). But this solution doesn't solve my problem because if the user scrolls the entire table, the whole resultset will be downloaded...
    In my opinion, there is only one solution:
    - create a small JTable "cache structure" and update the structure with "remote calls" to the server ...
    in other words I have to define on the server side a "servlet environment" that queries the database, creates the resultset and gives to the jtable only the data subsets that it needs... (alternatively I could define an RMI client/server distribuited applications...)
    This is my solution, somebody can help me?
    Are there others solutions for my problem?
    Thanks in advance,
    Stefano

    The database table currently is about 80000 rows but the next year will be 200000 and so on ...
    I know that excel has this limit but my JTable have to display more data than a simple excel work sheet.
    I explain in more detail my solution:
    whith a distribuited TableModel the whole tablemodel data are on the server side and not on the client (jtable).
    The local JTable TableModel gets the values from a local (limited, 1000rows for example) structure, and when the user scroll up and down the jtable the TableModel updates this structure...
    For example: initially the local JTable structure contains the rows from 0 to 1000;
    the user scroll down, when the cell 800 (for example) have to be displayed the method:
    getValueAt(800,...)
    is called.
    This method will update the table structure. Now, for example, the table structure will contain data for example from row 500 to row 1500 (the data from 0 to 499 are deleted)
    In this way the local table model dimension will be indipendent from the real database table dimension ...
    I hope that my solution is more clear now...
    under these conditions the only solutions that can work have to implement a local tablemodel with limited dimension...
    Another solution without servlet and rmi that I have found is the following:
    update the local limited tablemodel structure quering the database server with select .... limit ... offset
    but, the select ... limit ... offset is very dangerous when the offset is high because the database server have to do a sequential scan of all previuous records ...
    with servlet (or RMI) solution instead, the entire resultset is on the server and I have only to request the data from the current resultset from row N to row N+1000 without no queries...
    Thanks

  • The product version and database version are not compatible

    The following simple program gets an exception {The product version and database version are not compatible} its very hard to proceed from here. Does anybody know what cause this?  
    Best Regards
    Jan Isacsson
    using System.Collections.ObjectModel;
    using Microsoft.MasterDataServices.Deployment;
    using Microsoft.MasterDataServices.Services.DataContracts;
    namespace MdsDeploy
        class Program
            static void Main(string[] args)
                try
                    ModelReader reader = new ModelReader();
                    Collection<Identifier> models = reader.GetModels();
                    foreach (Identifier modelId in models)
                        Console.WriteLine(modelId.Name);
                catch (System.Exception ex)
                    Console.WriteLine("Error: " + ex.Message);
                Console.ReadKey();

    Hi Jan,
    For the error "The product version and database version are not compatible", as Emma said, the version number of the Service does not match the database schema version.
    In your scenario, which version of database are you using? Please note that MDS update required after SQL 2012 SP1 installation, please refer to the links below to see the details.
    http://byobi.com/blog/2012/11/mds-update-required-after-sql-2012-sp1-installation/
    http://msdn.microsoft.com/en-IN/library/gg488708.aspx
    Regards,
    Charlie Liao
    TechNet Community Support

  • Error #1015: Database Communication Error

    Hi,
    I am having a WebCTRL application on my infra which is connecting to SQL server 2008 R2.
    On application side, we are frequently getting error messages saying that ,
     Error #1015: Database Communication Error   --   Critical problem occurred (With timings) Reestablished (DBname) database connection.     details: Successfully reconnected to the database
    i dont see any errors on SQL server logs as well as event logs on the server.
    Is it happening because of SQL server ?
    Is there anything i missed to check ? 
    Please help me to solve this issues.
    Regards,
    Vinodh Selvaraj

    Can you check if your database properties set Auto Close to ON , it must be set to OFF
    https://msdn.microsoft.com/en-us/library/bb402929.aspx
    Best Regards,Uri Dimant SQL Server MVP,
    http://sqlblog.com/blogs/uri_dimant/
    MS SQL optimization: MS SQL Development and Optimization
    MS SQL Consulting:
    Large scale of database and data cleansing
    Remote DBA Services:
    Improves MS SQL Database Performance
    SQL Server Integration Services:
    Business Intelligence

  • JTable + update database

    hey all!!!
    i ve been searching the internet for a while but i don't seem to be able to find any solution to my problem. well, what i want to do is this...
    i have mysql db connected to my applets. i select from table and show the result in JTable on the interface. it all good and well but i am wondering whether it possible to update the table and then, let's say press button, and also update the databse or not?? what i mean is whether i have to press the button get values in the corresponding row, load the values into JTextFields and then press another button and update the database or whether i can just change the JTable and then press only one button and everything that's in the JTable will get, magically, updated in the database without having to use the middle JTextField step??
    v.v.

    are you a soldier??No, but I served in the Navy for 5 years.
    >
    thanks that's exactelly what i needed.... will give
    it a read
    v.v.You're welcome; happy reading.

  • Lifecycle Workflow platform and database sizing guide?

    I've been asked to investigate the technical aspects of the Lifecycle Workflow and Reader Extension products.
    I've gone through the various adobe websites a great deal and found installation guides but nothing that provides platform selection and database sizing recommendations.
    We are considering both JBoss on Suse LInux and WebSphere on AIX as a platform.
    Is anyone aware of any recommendations as to the choice of a platform?
    Any experiences or recommendations out there from the user community?
    Also, is there any documentation that gives guidance to database sizing? Frankly, I'm not sure I understand yet whether it's just the routing/metadata that gets stored in the workflow database or the actual documents as well.
    Anyone point me at or provide me more technical documentation?
    Thanks
    Verlyn

    Hi Verlyn
    I can answer some of your questions, based on my understanding.
    The workflow engine does store the document itself as part of the workflow. In fact, it records the historical state of the document at each point that someone in the workflow worked on it. You can see this by looking at the "Participated" item in Form Manager, where you can see the historical value of each form that's been submitted. Any workflow attachments are also stored in the database.
    It gets a little more complicated. Depending on how you structure your workflow, you can choose to either store the entire PDF (in a document or binary variable) or just the data (in a form variable -in which case the data is merged with an xdp template whenever someone wants to view it).
    Document variables are also a little more intelligent: you can specify a size threshold. Below that threshold, the document is stored as a blob in the database - above the threshold, the document is stored in a folder on the file system. The default threshold value is 64K.
    I hope this helps...
    Howard Treisman
    http://www.avoka.com

  • JFrame With Two JTables Accessing Database;  Last Table Partial Display

    I have an application that calls a JFrame in a database application. The JFrame contains a number of panels, two of which are dedicated to JTables.
    The first JTable,upon completion of a resultset, displays master records for the application. Immediately upon completion, the second JTable should be displaying details related to the selected master (on first retrieval, the second Jtable should reflect details related to the first displayed record in the first JTable).
    The first JTable displays correctly. The second only displays one record, even though thru inserted System.out.println statements, I can track the number of rows that should be there.
    The first JTable fills and then calls a function filldetl(). This is the code:
    +
    private void filldetl() {
    try
    details.setRowCount(0);
    Statement t = conn.createStatement();
    ResultSet dt; // for look up
    dt = t.executeQuery("select sku,skuqty,skuunit,value," +
    "skucurrency,skuorigin,htc from rcvrdtl " +
    "WHERE invoiceno = '" + +invno< </em>
    "' ORDER BY invoiceno;");
    dd = dt.getMetaData();
    *int< </strong>columnct = dd.getColumnCount();
    System.+out+.println("Columns found = " + String.+valueOf+(columnct));
    // Set up variable dbrowcount to find number of rows in resultset.
    int dbrowcount = 0;
    while *true*==dt.next()) {
    dbrowcount++;
    rowx = *new< </strong>Vector(columnct);
    datax = new Vector();
    for *int< </strong>x = 1; x <= columnct; x++) {
    rowx.addElement(dt.getObject(x));
    datax.addElement(rowx);
    int rowNumx = dt.getRow();
    System.+out+.println("Rows Found = " + String.+valueOf+(dbrowcount));
    System.+out+.println("Located At Row " + String.+valueOf+(rowNumx));
    for *int< </strong>x = 0; x < datax.size(); x++) {
    details.addRow((Vector)datax.elementAt(x));
    jTable1.revalidate();
    jTable1.setRowSelectionInterval(0,0);
    catch (Exception et) {
    System.+out+.println(et.getMessage());
    et.printStackTrace();
    +
    Can anyone tell me why I am only getting one record displayed in the second JTable, even though there are more? the variable dbrowcount keeps track of how many detail records there should be. And I have verified the counts by checking records in the database.
    What am I doing wrong?
    Any help appreciated....
    Thanks
    VazCro

    This is the code as it should be. I don't know why it was trashed:
         private void filldetl() {
              try {
                   details.setRowCount(0);
                   Statement t = conn.createStatement();
                   ResultSet dt; // for look up
                   dt = t.executeQuery("select sku,skuqty,skuunit,value," +
                             "skucurrency,skuorigin,htc from rcvrdtl " +
                        "WHERE invoiceno = '" + invno +
                        "' ORDER BY invoiceno;");     
                   dd = dt.getMetaData();
                   int columnct = dd.getColumnCount();
                   System.out.println("Columns found = " + String.valueOf(columnct));
                   // Set up variable dbrowcount to find number of rows in resultset.
                   int dbrowcount = 0;
                   while (true==dt.next()) {
                        dbrowcount++;                
                        rowx = new Vector(columnct);
                        datax = new Vector();
                        for (int x = 1; x <= columnct; x++) {
                             rowx.addElement(dt.getObject(x));
                        datax.addElement(rowx);
                   int rowNumx = dt.getRow();
                   System.out.println("Rows Found = " + String.valueOf(dbrowcount));
                   System.out.println("Located At Row " + String.valueOf(rowNumx));
                   for (int x = 0; x < datax.size(); x++) {
                        details.addRow((Vector)datax.elementAt(x));
              jTable1.revalidate();
                   jTable1.setRowSelectionInterval(0,0);
              catch (Exception et) {
                   System.out.println(et.getMessage());
                   et.printStackTrace();
    I am calculating how many records were found for the second JTable and going thru the routines to load the second JTable. However, only one record appears.
    Thanks for your help.
    VazCro

Maybe you are looking for

  • I updated iTunes and now my 6th generation nano can't be properly recognized now.

    I recently updated my iTunes after holding off for a bit and now my 6th generation Nano wn't be recognized in iTunes but is recognized on the computer. The message I get is this "An iPod has been detected, but it could not be identified properly. Ple

  • AVC H264 720p60 video with AC-3 asynchronous after exporting as AVCHD using Pre11

    Dear community, I am currently facing a problem concerning asynchronous video and sound after rendering AVC files including H264 codec at 720p60 and AC3 sound as well as multiple stereo tracks. The video is recorded using Hauppauge Hauppauge HVR-5500

  • Aperture regards masters as previews

    Hi, I recently moved from iPhoto to Aperture. I opened my existing iPhoto library, which holds 25k pictures, in Aperture (so I did not use the File -> Import option, I simply opened the existing iPhote library). Out of the 25k photos, roughly 500 of

  • Cisco LMS 4.2.3 - Nexus VDC - SNMP

    Hi All, I am having some trouble with getting inventory collection work for the VDC's of a Nexus 7k from LMS 4.2.3. The collection works for the main VDC, just not any of the others. I have verified (using SNMPWALK) from the LMS server that the snmp

  • WLS 6.0 & WLCS 3.2 & interop between 5.1 & 6.0

    Hi, Apparently, WLCS 3.2 will support WLS 6.0 in spring (cf various posts). We are currently using WLS 5.1 for EJB dev & WLCS for JSP dev but wanted to migrate our EJB dev to WLS 6.0. Not possible !!! We thought of having two servers one for running