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

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 ?

  • 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

  • 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.

  • 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.

  • 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.

  • Performance with MySQL and Database connectivity toolbox

    Hi!
    I'm having quite some problems with the performance of MySQL and Database connectivity toolbox. However, I'm very happy with the ease of using database connectivity toolbox. The background is:
    I have 61 variables (ints and floats) which I would like to save in the MySQL-database. This is no problem, however, the loop time increases from 8ms to 50ms when using the database. I have concluded that it has to do with the DB Tools Insert Data.vi and I think that I have some kind of performance issue with this VI. The CPU never reach more the 15% of its maximum performance. I use a default setup and connect through ODBC.
    My questions are:
    1. I would like to save 61 variables each 8-10ms, is this impossible using this solution?
    2. Is there any way of increasing the performance of the DB Tools Insert Data.vi or use any other VI?
    3. Is there any way of adjusting the MySQL setup to achieve better performance?
    Thank you very much for your time.
    Regards,
    Mattias

    First of all, thank you very much for your time. All of you have been really good support to me.
    >> Is your database on a different computer?  Does your loop execute 61 times? 
    Database is on the same computer as the MySQL server.
    The loop saves 61 values at once to the database, in one SQL-statement.
    I have now added the front panel and block diagram for my test-VI. I have implemented the queue system and separate loops for producer and consumer. However, since the queue is building up faster then the consumer loop consumes values, the queue is building up quite fast and the disc starts working.
    The test database table that I add data to is created by a simple:
    create table test(aa int, bb char(15));
    ...I'm sure that this can be improved in some way.
    I always open and close the connection to the database "outside the loop". However, it still takes some 40-50 ms to save the data to the database table - so, unfortunatly no progress to far. I currently just want to save the data.
    Any more advise will be gratefully accepted.
    Regards,
    Mattias
    Message Edited by mattias@hv on 10-23-2007 07:50 AM
    Attachments:
    front panel 2.JPG ‏101 KB
    block diagram.JPG ‏135 KB

  • 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

  • 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.

  • 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

  • Installing DBI and DBD::mysql in 10.4 Tiger, with MySQL 5.0

    After some discussion here http://discussions.apple.com/thread.jspa?threadID=546982&tstart=0
    I wanted to document what was required to get Bundle::DBI and DBD::mysql installed.
    I started off with the helpful info found on the following two pages, but I had to do more to get it working:
    http://www.truerwords.net/articles/osx/installdbdmysql.html
    http://www.gyford.com/phil/writing/2004/06/07/installingdbia.php
    Note: I am working with mysql-standard-5.0.15-osx10.4-powerpc,
    downloaded and configured according to the MySQL site instructions.
    If you are using an earlier version of MySQL, then you will need to adjust accordingly. The articles I link to above, may work for you verbatim.
    1. Download DBI 1.51 from CPAN:
    http://search.cpan.org/~hoymich/DBI-1.45-5.8.4/
    2. Unpack the file, eg: tar -xzvf DBI-1.51.tar.gz
    3. cd into the directory
    4. Type perl Makefile.PL
    5. Type make && make test
    6. sudo make install (NB: See below !)
    7. IMPORTANT: to get DBD to install, you may need to specify the location of your mysql_config file:
    perl Makefile.PL --testdb=test --testuser=nameused --testpassword=actualpasswdused --testhost=localhost --mysqlconfig=/usr/local/mysql/bin/mysqlconfig
    If something goes wrong, backup by typing:
    make clean
    Another note: I granted full priveleges for the "test" user on the "test" database, which is accepting local connections only and will be removed after everything is configured.
    # now for DBD
    8. Download DBD::mysql from CPAN http://search.cpan.org/~capttofu/DBD-mysql-3.0006
    9. unpack the archive & cd into it
    10. perl Makefile.PL --testdb=test --testuser=nameused --testpassword=actualpwdused --testhost=localhost
    11. make && make test
    12. sudo make install
    That's what it took, hopefully this will help others who need it, and not offend those who know more about it

    Hi David!
    I'm trying to help my incredibly frustrated boyfriend, who's trying to upgrade to Tiger on his 12" PB (1.3 MHz single processor).
    He does a lot of web design and development, so he formatted his drive as HFS+, case-sensitive, journaled, and has installed his Adobe apps on a dmg, which works great.
    BUT (and he says this is always a problem) installing DBD::mySQL is proving near-impossible! His install is failing 98% of the tests run during maketest. He thinks the problem may actually be occurring when he runs Makefile. Here's the error message he's getting, even after reading your posts:
    During Makefile.PL:
    Can't exec "mysql_config": No such file or directory at Makefile.PL line 450.
    Do you have any idea of a direction to point him in? He's so frustrated he can't even post to the forum - language not suitable for family viewing at this time.
    Thanks!
    Natalie
    Dual 867MHz G4 MDD   Mac OS X (10.3.6)  

  • 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

  • Java and database

    I want to develop an application software using java however i dont know which data base systems / software to use apart from mysql, and access. Is sql just a language or is it also a database software
    please help

    OK, that enough, but just to set the record straight. You said "SQL is a software too", no it is not. SQL is a language.
    http://en.wikipedia.org/wiki/SQL
    SQL (IPA: /&#716;&#603;s&#716;kju??&#712;&#603;l/ or /&#712;si??kw&#601;l/), commonly expanded as Structured Query Language, is a computer language designed for the retrieval and management of data in relational database management systems, database schema creation and modification, and database object access control management
    Some companies, such as Microsoft (not "windows"), make products, such as SQL server, with "SQL" in the title. But SQL Server is:
    Microsoft SQL Server 2005 is a comprehensive, integrated data management and analysis software
    http://www.microsoft.com/sql/prodinfo/overview/default.mspx

Maybe you are looking for

  • Why does my signal drop every time I try to use an application.

    I've got a UFO style 802.11g, which I unfortunately kept up to date with the updates. For well over a year now I've had my gear set up like this, airport in the den, my wife's older Imac in the den with it, the printer in the den as well and my Imac

  • Java mapping and monitoring

    Hello, does anybody know how to send tracing information to the XI monitor(SXMB_MONI) from within a Java mapping / XSLT mapping. Thank you /Ernesto

  • My iPhone 4S is BENT??

    Hi, this may sound stupid but my iPhone 4S White is actually BENT/DEFORMED. It isnt flat like iPhones are supposed to be, it actually bends/curves toward the front of the iPhone. If you hold it screen facing the sky and in landscape formation, you ca

  • Yesterday it worked perfectly, now it won't start up.

    Hello there, My pc is working on Windows Vista, no problems. Yesterday (and before) all worked perfectly and to day I have downloaded my email, used I.E. but my mozilla firefox won't start up. I have (double) checked the registry for flows (with Regi

  • Lightroom 5 not showing in my applications folder

    Although I have installed lightroom 5 and it is showing as up to date in the new creative cloud interface, I cannot see it anywhere in my application folder. I am therefore unable to open it. I have logged out and back in again to my account and rest