Updating a database from a JTable

So, in my GUI class, the user searches for the records of an event and round, which returns 9 records into my JTable for me.
This is how i do thi
else { List<UpdateEventSetGet> searchResult = sql.searchRecords(sType, sType2); for(int x = 0, y = searchResult.size(); x < y; x++) { UpdateEventSetGet update = searchResult.get(x); model.setValueAt(update.getNationality(), x, 0); model.setValueAt(update.getFirstname(), x, 1); model.setValueAt(update.getLastname(), x, 2); model.setValueAt(update.getTime(), x, 3); } }
Now with user being able to see their search results in the JTable, they are able to edit it. Then once they click update, the new edited JTable should be updated into my database. Whats the best way to achieve this update? I was thinking about just taking the whole table model and sending that off to my database to replace what is there. But then what happens if they only change one word, is it a waste to change everything? Whats the best way to achieve this update?
Any Advise?

nick2price wrote:
Sorry, when i say table i am making a bad reference to my table model, I meant the table model. What i am just trying to understand better is the actual update statement. So lets say the user updates one cell in the JTable, wouldnt the update need to be specific to that cell? So if you had a table model with four columns, Nationality, First_Name, Last_Name and Time_Set. This model also has 9 rows of data. Now i dont know what cells the user is going to update. So how is it possible to make an update statement for this?Well, come on. One of the columns is the table's primary key, right? So you don't let the user change that column. If they change any other column, you execute an update like
Update Table set Column5='Simple' where Column1='Key"{code}
Of course whichever column they update, you update the corresponding column in the database. You could make things more complicated, but why not just keep it simple?                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

Similar Messages

  • Connecting and Updating External Database from SAP

    Connecting and Updating External Database from SAP
    How can i connect SAP Database to External database?
    How can i update external databas from SAP withouting using BI/BW, Workflow or Net Weaver?
    If anyone know please let me inform.
    Thanks in Advance.
    Jahnavee Trivedi

    Steps
    1. Create an entry in tnsnames.ora for the remote oracle DB
    2. Test sqlplus user/pass@remote 
    3. create a synonym which points to a table at remote DB check docs.oracle.com
    4. user ABAP code execute SQL to insert data into local synonym which inturn updates the remote DB.
    I have done this in the past, it works great.
    It requries, DBA skills + ABAP programming
    -AJ

  • Best way to update DR database from PROD server automatic ?

    Hello Gurus,
    I want to decide best solution.
    Goal: Best way to update DR Database from PROD Server Database automatic.
    System: 32 bit Linux system with Oracle Database 10g Release 10.2.0.4.0 - Production (database version) Oracle version is standard.
    Please let me know how i can update my DR server with PROD data and this task should be automatic.
    Please ask me more information if required to solve this issue.
    Thanks- Priyank
    Edited by: Oracle DBA P on Nov 19, 2010 3:06 AM

    you mean to say data guard needs to implement ? i think that's one option but what you said is different ?
    tell me procedure how i can implement your idea ? steps i have to perform.
    Thanks
    Edited by: Oracle DBA P on Nov 19, 2010 3:38 AM

  • Trouble updating a JtextArea from a JTable ListSelectionListener..

    Hi, I'm having trouble updating a JtextArea from a JTable ListSelectionListener, it is working for another JTextArea but I have created JNMTextArea which extends JTextArea and I am getting no data passed to it.
    Any help is really greatly appreciated. Im a relative newbie to Java.
    Here is the class declaration for JNMTextArea
    public class JNMTextArea extends JTextArea
         //Constructor
         public JNMTextArea(String text){
              super(text);
              setLineWrap(true);
              setEditable(false);
         //Constructor
         public JNMTextArea()
              this(new String());
         //This sets the data in setText, works ok.
         void displayPacket(Packet p){
              //Function works fine
              //Need to pass this data to the JNMTextArea!!!
              setText(buffer.toString());
              setCaretPosition(0);
    Here is where I use JNMTextArea, Im
    class JNMGui extends JFrame implements ActionListener, WindowListener{
         public static JNMTextArea txtPktContent;
         //Constructor
              JNMGui(){
                   buildGUI();
         private void buildGUI(){
         mainWindow = new JFrame("Monitor");
         tblPacket = new JTable(tblPacketM);
         tblPacket.setToolTipText("Packet Panel");
         tblPacket.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
         if (ALLOW_ROW_SELECTION) {
              ListSelectionModel rowSM = tblPacket.getSelectionModel();
              rowSM.addListSelectionListener(new ListSelectionListener() {                     public void valueChanged(ListSelectionEvent e) {
                        if (e.getValueIsAdjusting())
                             return;
                        ListSelectionModel lsm =      (ListSelectionModel)e.getSource();
                        if (lsm.isSelectionEmpty()) {
                             System.out.println("No rows are selected.");
                        else {
                             int selectedRow = lsm.getMinSelectionIndex();
                             selectedRow++;
                             String str;// = "";
                             //Unsure if I need to create this here!
                             txtPktContent = new JNMTextArea();
                             //This works perfectly
                             txtPktType.append ( "Packet No: " + Integer.toString(selectedRow) + "\n\n");
                             Packet pkt = new Packet();
                             pkt = (Packet) CaptureEngine.packets.elementAt(selectedRow);
                             if(pkt.datalink!=null && pkt.datalink instanceof EthernetPacket){
                                  str = "Ethernet ";
                                  //THis works txtPktType is another JTextArea!!          
                                  txtPktType.append ( s );
                                  //This is not working
                                  //I realise displayPacket return type is void but how do get
                                  //the setText it created to append to the JNMTextArea??               
                                  txtPktContent.displayPacket(pkt);
              //Adding to ScrollPane
              tblPane = new JScrollPane(tblPacket);
              txtPktTypePane = new JScrollPane ( txtPktType );
              txtPktTypePane.setToolTipText("Packet Type");
              txtPktContentPane = new JScrollPane ( txtPktContent );
              txtPktContentPane.setToolTipText("Packet Payload");
              panel.add( tblPane, BorderLayout.CENTER );
    //End Class JNMGui

    void displayPacket(Packet p){
              //Function works fine
              //Need to pass this data to the JNMTextArea!!!
              setText(buffer.toString());
              setCaretPosition(0);
    This seems really odd. Notice that you pass in "p" but use "buffer". Where is "buffer" defined?

  • Updating standby database from primary using rman

    I have created a standby database using rman on my oracle linux server, now i want to update the standby from my primary database, but i didn't remember the scn which i used for creating the standby. How can i find out the scn from where i should perform the incremental backup on the primary, so that i can update my standby database with the latest information.

    You simply need to find out which logs on the Primary have yet to be applied to your Standby. Have a look at this (or any Oracle Data Guard docs.): http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10823/manage_ps.htm#1024046
    As long as the logs are available on the Primary server, then they should be sent across to the Standby server. Use the views described in the above link to check for any gaps, etc.

  • How to update a database from an MS Excel

    Hi,
    I'm developing an application that would let the user view and edit the data from the database through Excel. My problem is, I need to update the database after the data was modified from MS Excel that doesn't need manual intervention.
    Thanks,
    mangyan

    At the risk of encouraging newbies to ask Microsoft specific questions on this Sun site...... the arch-enemy of Microsoft.....
    You can write a VB Macro to execute when the user clicks a button / control on the spreadsheet to say "Commit to database".
    Or maybe ask the user just before they close the database.
    VB has various database methods, like OpenDatabase.
    See examples in the Macro editor.
    Or if you want to give yourself an ounce of self respect, you could write a JSP application to input the values, and update a database via JDBC.
    regards,
    Owen

  • Updating test database from production in Oracle 10g

    What will be easiest way to have production database replicated to test database once a day basis? The 2 databases are on similar machines & same OS

    What sort of test system are you building? Are you building a reporting server so you can run reports on a snapshot of the data? Are you building a staging environment where you can test applying scripts and can simply reapply the DDL changes every day? Or do you have a real testing instance which will generally have slighly different table definitions/ objects/ etc than the production instance?
    Justin
    Distributed Database Consulting, Inc.
    http://www.ddbcinc.com/askDDBC

  • Update database from Jtable

    Hi all,
    I am trying to update database from Jtable. I added Jtable to scrollpane .
    My question is..
    after updating the Jtable..I want to save the details to database..when I click save button on my screen...how to do that? Please help me out! Thanks in advance..
    Here is the code that I wrote...
    public class VasuTest extends JFrame {
    private boolean DEBUG = true;
    Vector column_list = new Vector();
    Vector rows = new Vector();
    public VasuTest() {
    super("VasuTest");
         JToolBar toolBar = new JToolBar();
    JButton button = null;
    button = new JButton("Send Email");
    button.setToolTipText("This is the Exit button");
    button.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
         System.out.println("Send Email");
    toolBar.add(button);
    button = new JButton("Save");
    button.setToolTipText("This is the Save button");
    button.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
         System.out.println("Save");
    toolBar.add(button);
    button = new JButton("Exit");
    button.setToolTipText("This is the Exit button");
    button.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
         System.exit(0);
    toolBar.add(button);
         JPanel ContentPane = new JPanel();
    ImageIcon i1 = new ImageIcon("Dongle.gif");
    JLabel j1 = new JLabel( i1, JLabel.CENTER);
         ContentPane.add(j1,BorderLayout.CENTER);
         setContentPane(ContentPane);
         JDBCT myModel = new JDBCT();
    String q = "select a.email_no,a.email_ln_no,b.cust_no,null customer_name,null cdate,a.batch_no,b.purch_ord_no,a.user_part_no,null part_desc,a.user_upgraded_part_no,null prod_id,a.qty,a.price,a.encrypted_sum_id,a.decrypted_sum_id,a.approval_key,a.status_cd,decode(a.status_cd,'APPROVED','true','ERROR','false','PROCESSED','true') approved,null end_cust,null sales_ord,null so_line,null sales_ord_cust,null shipment ,null sales_end_cust_name ,null shipment_line,a.note,null fromcust from upgrade_req_key_s3 a,upgrade_req_s3 b where a.email_no = b.email_no order by a.email_no,a.email_ln_no";
    myModel.setQuery();
    final Font f = new Font("SansSerif", Font.BOLD, 10);
    JTable table = new JTable(myModel);
    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    // Container ContentPane = getContentPane();
         int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS;
         int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS;
         JScrollPane scrollPane = new JScrollPane(table,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
         scrollPane.setPreferredSize ( new Dimension ( 770, 400 ) );
    ContentPane.add(toolBar,BorderLayout.CENTER);
    //Add the scroll pane to this window.
    ContentPane.add(scrollPane,BorderLayout.CENTER);
    addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    public class JDBCT extends AbstractTableModel {
    Vector cache; // will hold String[] objects...
    int colCount;
    int rowHeight;
    String [] headers;
    Connection db;
    Connection conn;
    Statement statement;
    String currentURL;
    // public QueryTableModel() {
    // cache = new Vector();
    // new oracle.jdbc.driver.OracleDriver();
    try {
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    catch (ClassNotFoundException e) {
    System.out.println(e.getMessage());
    System.exit(-1);
    String url = "jdbc:odbc:c3-erp,s3,s3";
    public String getColumnName(int i) {
         if (i == 0)      {  return      "Email No"                     ;     } else
    if (i == 1)      {  return      "Email Line No.";} else
         if (i == 2)      {  return      "Customer";} else
         if (i == 3)      {  return      "Customer Name";} else
         if (i == 4)      {  return      "Date";} else
         if (i == 5)      {  return      "Batch No";} else
         if (i == 6)      {  return      "Customer PO";} else
         if (i == 7)      {  return      "Upgrade From Part";} else
         if (i == 8)      {  return      "Part Description";} else
         if (i == 9)      {  return      "Upgrade To Part";} else
         if (i == 10)      {  return      "Product Id";} else
         if (i == 11)      {  return      "Quantity";} else
         if (i == 12)      {  return      "Price";} else
         if (i == 13)      {  return      "Encypted Sum ID";} else
         if (i == 14)      {  return      "Decrypted Serial No";} else
         if (i == 15)      {  return      "Key";} else
         if (i == 16)      {  return      "Status";} else
         if (i == 17)      {  return      "Approved";} else
         if (i == 18)      {  return      "End Customer";} else
         if (i == 19)      {  return      "Sales Order";} else
         if (i == 20)      {  return      "SO Line";} else
         if (i == 21)      {  return      "Sales Order End Customer";} else
         if (i == 22)      {  return      "Sales Order End Customer Name";} else
         if (i == 23)      {  return      "Shipment";} else
         if (i == 24)      {  return      "Shipment Line";} else
         if (i == 25)      {  return      "Errors";} else
         if (i == 26)      { return       "From"; }
         else {return headers[i-1] ;}
    public int getColumnCount() { return colCount; }
    public int getRowCount() { return cache.size(); }
    //public Class getColumnClass(int c) {
    // return getValueAt(0, c).getClass();
    // overloaded isCellEditable method so that it returns true
    // in reference to a cell being editable.
    public boolean isCellEditable(int row, int col) { return true; }
    // overloaded setValyeAt which updates the data Vector and
    // calls the fireTableRowsUpdated() to notify any listeners
    // that data has changed and they need to redraw.
    public void setValueAt(Object value, int row, int col) {
    ((String[])cache.elementAt(row))[col] = (String)value;     
         fireTableRowsUpdated(row,row);     
    public void getInfo () {
    System.out.println("Row Count is : " + cache.size());
         System.out.println("Value at 0,0 is : " + getValueAt(0,0));
    //     boolean res = isCellEditable(0,0);
    //     System.out.println("The value of the Boolean result is : " + res);
    public Object getValueAt(int row, int col) {
    return ((String[])cache.elementAt(row))[col];
    // All the real work happens here!
    // In a real application, we'd probably perform the query in a separate thread.
    public void setQuery() {
    cache = new Vector();
    try {
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    conn = DriverManager.getConnection ("jdbc:odbc:c3-erp","s3","s3");
    Statement stmt = conn.createStatement();
    ResultSet rs = stmt.executeQuery("select a.email_no,a.email_ln_no,b.cust_no,null customer_name,null cdate,a.batch_no,b.purch_ord_no,a.user_part_no,null part_desc,a.user_upgraded_part_no,null prod_id,a.qty,a.price,a.encrypted_sum_id,a.decrypted_sum_id,a.approval_key,a.status_cd,decode(a.status_cd,'APPROVED','true','ERROR','false','PROCESSED','true') approved,null end_cust,null sales_ord,null so_line,null sales_ord_cust,null shipment ,null sales_end_cust_name ,null shipment_line,a.note,null fromcust from upgrade_req_key_s3 a,upgrade_req_s3 b where a.email_no = b.email_no order by a.email_no,a.email_ln_no");
    ResultSetMetaData meta = rs.getMetaData();
    colCount = meta.getColumnCount();
    String[] record = new String[27];      
    // Now we must rebuild the headers array with the new column name
    headers = new String[27];
    for (int h=0; h < 27; h++) {
    // headers[h-1] = meta.getColumnName(h);
         headers[h] = getColumnName(h);
    // and file the cache with the record from our query. This would
    // be practical if we were expecting a few million records to our
    // response query, but we are not so we can do this.
    while(rs.next()) {
         for (int i=0; i < colCount; i++) {
         record[i] = rs.getString(i + 1);
         cache.addElement(record);
         // Get the FIRST column of the table tableView
    // TableColumn column0 = table.getColumn(cache.elementAt(0));
    // Set the cell editor as non editable.
    // column0.setCellEditor(new EditableCellEditor(new JComboBox(), true));
    fireTableChanged(null); // notify everyone the we had a new table.
    catch (Exception e) {
    cache = new Vector(); // blank it out and keep going.
         e.printStackTrace();
    public static void main(String[] args) {
    VasuTest frame = new VasuTest();
    frame.pack();
    frame.setVisible(true);
    }

    When you click on the save button, you need to go through the model and retrieve the values getValueAt().
    Convert to whatever type you want since getValueAt() returns type Object and update the DB.

  • How to edit databases from JTable?

    Hello everyone, I would like to ask your help on how we can edit JTable cells that would be reflected into the database, or how do we change the database via a JTable.
    I have the installer of an application which I made with Java SE called FuelStation.exe
    My class files are ready for sharing along with its source files.
    I have placed it in this location in my website:
    http://www.apachevista.com/alphaprojects/runfiles/
    It is complete with full details about databases, proposed mysql embed, and so on. Please see the file and notify me at [email protected]
    Here is my sample code:
    // 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");
    final String JDBC_DRIVER = bundle.getString("Driver");
    final String DATABASE_URL = bundle.getString("URL");
    final String USERNAME = bundle.getString("User");
    final String PASSWORD = bundle.getString("Password");
    // default query retrieves all data from authors table
    //static final String DEFAULT_QUERY = "SELECT authors.lastName, authors.firstName, titles.title, titles.editionNumber FROM titles INNER JOIN (authorISBN INNER JOIN authors ON authorISBN.authorID=authors.authorID) ON titles.isbn=authorISBN.isbn";
    final String DEFAULT_QUERY = bundle.getString("Query");
    private ResultSetTableModel tableModel;
    private JTextArea queryArea;
    static final int xOffset = 0, yOffset = 200;
    private boolean ALLOW_COLUMN_SELECTION = false;
    private boolean ALLOW_ROW_SELECTION = true;
    // 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
    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 DisplayQueryResults
    My question is in lines 177-187:
    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");
    Why is my listener not working or why is it not implemented when I click the cells in the JTable and why is it not reflected into the JTable or into the console?
    If this is Flash, Things can be done easily, but this is Java, and I dont know much about this language. I admit that I am new to this -intirely new.
    PS:
    When you have solved the problem, please notify me with the code that's changed
    and please share it to others if you like so.
    Best Wishes: Oliver Bob Lagumen
    Email: [email protected]
    website: www.apachevista.com
    Oliver Bob Lagumen
    Edited by: Oliverbob on Jan 24, 2008 9:03 PM

    Why is my listener not working or why is it not implemented when I click the cells in the JTable and why is it not reflected into the JTable or into the console?What does happen when you click on the cells?
    Does the ResultSetTableModel report the cells as editable? If not you will never get to edit their contents, and so the table's model won't change, and so the table model listener will never get invoked.
    When you post code here use the code tags. Basically you put {code} at the start of your code and again at the end. That way the code will be readable.
    Try to post minimal examples with which others can reproduce your problem. In this case "minimal" would involve removing or drastically simplifying a lot of the GUI stuff which is just noise. But "reproduce" would involve including the ResultSetTableModel.
    When you have solved the problem, please notify me with the code that's changedAvoid this.
    What you say here is quite possibly not what you mean. But, in any event, while there might be plenty of interest in helping with specific problems there will likely be none in writing your code. Your problem remains yours. But your solution and your code - prompted by whatever help you might recieve - will also be yours.

  • How to update data in database from different region of the same page

    Hi,
    I have pepared two regions of tabular form based on the same table,each region is selecting different columns of the same table.
    I want to update the values from different regions in the database using single submit button.
    Regards
    Shashi

    I presume that the two regions are working fine with their individual buttons and your issue is how to make them both save with one button.
    Here is how
    a. You will have 2 ApplyMRU and 1 ApplyMRD processes for each of the regions. Right? Lets say you have 2 "Save" (i.e. label=Save) buttons, one has name SUBMIT and the other SAVE ( SUBMIT and SAVE being the requests that will be sent when they are clicked , respectively)
    b. Make the Display condition on one of the buttons 'Never'. Now it won't show when you run the page. Lets say you made SAVE's conditional Display 'Never'
    c. Go and change the condition on all ApplyMRU and ApplyMRD processes from "When Button Pressed" to "Request is contains in Expression1". In Expression1 enter SUBMIT,SAVERegards

  • Editing MySQL Database from JTable

    Hello everyone, I would like to ask your help on how we can edit JTable cells that would be reflected into the database, or how do we change the database via a JTable.
    I have the installer of an application which I made with Java SE called FuelStation.exe
    My class files are ready for sharing along with its source files.
    I have placed it in this location in my website:
    http://www.apachevista.com/alphaprojects/runfiles/
    It is complete with full details about databases, proposed mysql embed, and so on. Please see the file and notify me at [email protected]
    Here is my sample code:
    // 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");
    final String JDBC_DRIVER = bundle.getString("Driver");
    final String DATABASE_URL = bundle.getString("URL");
    final String USERNAME = bundle.getString("User");
    final String PASSWORD = bundle.getString("Password");
    // default query retrieves all data from authors table
    //static final String DEFAULT_QUERY = "SELECT authors.lastName, authors.firstName, titles.title, titles.editionNumber FROM titles INNER JOIN (authorISBN INNER JOIN authors ON authorISBN.authorID=authors.authorID) ON titles.isbn=authorISBN.isbn";
    final String DEFAULT_QUERY = bundle.getString("Query");
    private ResultSetTableModel tableModel;
    private JTextArea queryArea;
    static final int xOffset = 0, yOffset = 200;
    private boolean ALLOW_COLUMN_SELECTION = false;
    private boolean ALLOW_ROW_SELECTION = true;
    // 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
    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 DisplayQueryResults
    My question is in lines 177-187:
    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");
    Why is my listener not working or why is it not implemented when I click the cells in the JTable and why is it not reflected into the JTable or into the console?
    If this is Flash, Things can be done easily, but this is Java, and I dont know much about this language. I admit that I am new to this -intirely new.
    PS:
    When you have solved the problem, please notify me with the code that's changed
    and please share it to others if you like so.
    Best Wishes: Oliver Bob Lagumen
    Email: [email protected]
    website: www.apachevista.com
    Oliver Bob Lagumen
    Edited by: Oliverbob on Jan 24, 2008 9:03 PM

    This is a follow up on the code I have posted above.
       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");
        }the tableChanged doesnt get called when I would click the cells. The cells are all editable, but as soon as you edit it and press enter, it snaps back to the old data.
    How do we make them editable and how do we notify java that the a cell has changed so that we can send it to the database on that specific column of that specific row?
    Thanks in advance
    Bob

  • HTML select tag on irpt page - update database from options

    Hi all,
    I have an irpt page with two selects.  It is the traditional move stuff from one select to the other, then set the order of the options in the configured select.  (Admin page to specify an ordered list of items)
    After the user gets the list how they want it, I would like to send the options to an MII transaction (iCommand?) to update the database table that backs this admin data.
    I can do a comma delimited string to hold the select tag's option values, but would like to know if there is a more elegant way!
    Ideas?
    Thanks,
    --Amy Smith
    --Haworth

    It sounds elegant already - a pretty simple javascript loop to build your csv and Param.1 to your iCommand applet query should work like a charm.
    If you need to run it to a TRX, then the StringListToXML action makes turning your csv into linkable properties a simple effort.

  • Database not updating with changes from SQL*plus

    I’m having some issues with updating my database. I want to delete some rows in a table that has 323 records, so I run the SQL in SQL*Plus. It tells me that I’ve deleted 222 rows. I then get a count of the number of rows in the table, and it tells me 101. But if I open another SQL*Plus window and get a row count, the original count (323) is what it says. The enterprise manager also tells me 323 records are in that table. Am I missing something here?

    Aimee-
    Until you 'commit' from the session you have issued the 'delete' statement, the other sessions will not be able to see the changes. In other words, the other sessions are getting you a read consistent view of the data.

  • Update Access database via OleDB from DataGridView

    I have been scouring these forums and the internet in general as well as doing a lot of reading, all to no avail.  I can not seem to successfully update the Access database from an edited DataGridView.  I am trying to use Stored Procedures that
    are in the Access database and work fine therein.  The DGV is filled in properly.  I have tried an ever-increasing number of variants to update the database (Private Sub BtnUpdate...)  without success.  I'd really, really appreciate some
    guidance here.
    Here is my code thus far:
    Public Class Form1
        Dim con As OleDbConnection    
        Dim cmd As OleDbCommand
        Dim da As OleDbDataAdapter
        Dim ds As DataSet
        Dim ProviderConnectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="
        Dim TargetList As String = "C:\Users\Administrator\Documents\Visual Studio 2010\Projects\Development5\Test.mdb"
        Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            'establish a connection to the database
            con = New OleDbConnection(ProviderConnectionString & TargetList)
            con.Open()
            'define the command to be used
            cmd = New OleDbCommand
            cmd.Connection = con
            cmd.CommandType = CommandType.StoredProcedure
            cmd.CommandText = "ListAllTargets"
             'create the data adapter based on the command
            da = New OleDbDataAdapter(cmd)
            'fill the data set based on the command
            ds = New DataSet
            da.Fill(ds, "AllTargets")
            'bind and load dgvTargets with the data
            dgvTargetList.DataSource = ds.Tables("AllTargets")  ' Binding to dgvtargetlist
         End Sub
        Private Sub btnUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpdate.Click
             da.UpdateCommand = New OleDbCommand("UPDATE TargetList SET;", con)
            Validate()
            da.Update(ds.Tables("AllTargets"))
            Me.ds.AcceptChanges()
        End Sub
    End Class

    Hi John,
    Welcome to MSDN forums!
    Cor pointed you to the right direction. An OleDBCommandbuilder object is required, which can be used to automatically
    generate DeleteCommand, UpdateCommand and InsertCommand for DataAdapter object.
    Here is detailed walkthrough: How to update
    (Insert/Update/Delete) data back into MS Access database from DataGridView.
    1) New a WinForms project, drag&drop DataGridView1 and Button1 onto
    Form1.
    2) Add database file test.mdb to project via: Data menu -> Add New Data Source
    Wizard ... then you can use ralative path to this database file in code
    3) Select/click
    your database file test.mdb in Solution Explorer
    -> Properties Pane
    -> change the "copy to ouput directory" to "copy
    if newer"
    4) Code sample
    Imports System.Data.OleDb
    Public
    Class Form1
    Dim myDA As OleDbDataAdapter
    Dim myDataSet As DataSet
    Private Sub Form1_Load(ByVal sender
    As System.Object, ByVal e
    As System.EventArgs) Handles
    MyBase.Load
    Dim con As OleDbConnection =
    New OleDbConnection("Provider=Microsoft.jet.oledb.4.0;data source=|DataDirectory|\test.mdb")  ' Use relative path to database file
    Dim cmd As OleDbCommand =
    New OleDbCommand("SELECT * FROM Table1", con)
    con.Open()
    myDA = New OleDbDataAdapter(cmd)
    'Here one CommandBuilder object is required.
          'It will automatically generate DeleteCommand,UpdateCommand and InsertCommand for DataAdapter object  
    Dim builder As OleDbCommandBuilder =
    New OleDbCommandBuilder(myDA)
    myDataSet = New DataSet()
    myDA.Fill(myDataSet, "MyTable")
    DataGridView1.DataSource = myDataSet.Tables("MyTable").DefaultView
    con.Close()
    con = Nothing
    End Sub
    ' Save data back into database  
    Private Sub Button1_Click(ByVal sender
    As System.Object, ByVal e
    As System.EventArgs) Handles Button1.Click
    Me.Validate()
    Me.myDA.Update(Me.myDataSet.Tables("MyTable"))
    Me.myDataSet.AcceptChanges()
    End Sub
    End
    Class
    Best regards,
    Martin Xie
    MSDN Subscriber
    Support in Forum
    If you have any feedback on our support, please contact
    [email protected]
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.
    Welcome to the All-In-One Code Framework! If you have any feedback, please tell us.

  • How to update data into database from mx datagrid?

    Hello,
         I am developing a native application. I have connected my application using HttpServices i.e. remote objects to spring mvc 2.5 application. I have done inserting and deleting data from database. Now I want to update the records from datagrid itself. I am new to AIR please suggesst me something useful.
         Thanks in advance..

    Likely you're querying only one selected value from the request using HttpServletRequest#getParameter() instead of an array of selected values using HttpServletRequest#getParameterValues().

Maybe you are looking for

  • Apple TV 2 Home Sharing depends on Source Device?

    So I've been running into an issue with Home Sharing on my Apple TV 2.  This is present on both the 4.2.2 and 4.3.2 firmware. (I own 2 Apple TV 2's. One vanilla and one running FireCore aTV Flash Black) When attempting to play back video content from

  • Won't Open flash files in the Browsers

    Hello..,      My created swf files are load and display through Java. If I run Java the Swf file will load with in that. After load the swf file I click on the flash environment and enter "CTRL+N" it opening in web Browser.      But I don't want for

  • Output Flatfile Conversion

    Hi All,        I am doing Flatfile to Flatfile scenario.My input format is like ID,Name,Address.I want to get the output which should be same like Input format but through mapping.I am using J2SE file Adapter in both sending and receiving side.I am g

  • Best Practice for Authorisations ?

    Dear All, We manage about 800 users in our SAP Production environment. We are on SAP R/3 4.7 Enterprise. Due to business changes and various requirements we need to often change the authorisations of end users at short notice. Presently each user has

  • Welcome! Please read before posting.

    Well hello there!   Welcome to our Let's Talk Games board - your and our place to rant & rave about the world of video games. You're gamers.  We're gamers.  Let's talk. Drawing a blank on what to discuss?  Here's some brain food... for you zombies: F