Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 7 of 7

Thread: jTable and jdbc

  1. #1
    Member
    Join Date
    Dec 2010
    Posts
    69
    My Mood
    Busy
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default jTable and jdbc

    I have my jTable populated with the data from a database using this code:
           try {
                String url = "jdbc:odbc:dts";
                String user = "";
                String password = "";
                Connection con = DriverManager.getConnection(url, user, password);
                lblConnect.setText("Successfully connected.");
                String getCust = "SELECT *  FROM Customer";
                PreparedStatement ps = con.prepareStatement(getCust);
                ResultSet rs = ps.executeQuery();
                while (rs.next()){
     
                    String s = rs.getString(1);
                    jTable1.setValueAt(s, R, 0);
                    s = rs.getString(2);
                    jTable1.setValueAt(s, R, 1);
                    s = rs.getString(3);
                    jTable1.setValueAt(s, R, 2);
                    s = rs.getString(4);
                    jTable1.setValueAt(s, R, 3);
                    s = rs.getString(5);
                    jTable1.setValueAt(s, R, 4);
                    s = rs.getString(6);
                    jTable1.setValueAt(s, R, 5);
                    s = rs.getString(7);
                    jTable1.setValueAt(s, R, 6);
                    s = rs.getString(8);
                    jTable1.setValueAt(s, R, 7);
                    R++;
     
               }
     
            } catch (Exception e) {
                lblConnect.setText("Connection Failed. Error A009");
            }
        }
    but can't figure out how I'd be able to implement a way for the user to be able to select the entire (already have it set to where once clicked, it highlights the row of data on the jTable) row and then click "Delete" button and it pick that exact row out and find it in the database and delete it.

    How would I get which row the user clicked before clicking the Delete button?


  2. #2
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,320
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: jTable and jdbc

    See the API for JTable (Java Platform SE 6) It has a method getSelectedRow (and getSelectedRows for multiple selection tables) which returns an integer of the row returned (or -1 for no selection). From there you can get the value(s) at that row in the JTable and remove it from the table and the database based upon the values.
    int row = table.getSelectedRow();
    if ( row != -1 ){
            String value = (String)table.getValueAt(row, 0);//column 1 value
           //delete from database given the value(s) to define the entry
    }

    As I mentioned in another post, I'd typically read in the data into objects, and create a DefaultTableModel based upon a List of these objects. Reason I mention this is because this allows you to store values that are in memory but no necessarily displayed in the table, which can help facilitate things down the line (for example a primary key in a database - which would identify a unique record to delete). As an example...
    int row = table.getSelectedRow();
    if ( row != -1 ){
            MyObject toDelete = myList.get(row);
           ///now you have ALL the data associated wrapped up in a single object
    }
    Last edited by copeg; March 4th, 2011 at 07:21 PM.

  3. The Following User Says Thank You to copeg For This Useful Post:

    _lithium_ (March 4th, 2011)

  4. #3
    Member
    Join Date
    Dec 2010
    Posts
    69
    My Mood
    Busy
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: jTable and jdbc

    Yeah it seems I really need to start reading the API more closely (although most of it makes stuff more complex then it is), I think the thing that is throwing me off is that when I learned Java I learned it all using TextPad and never used an IDE. This NetBeans is a different feel (and most commands i haven't used/heard of).


    Like now I can't figure out how to enable my btnDelete when someone clicks on the jTable. I know I used ActionListeners before but when I go netbeans' Event box and use the "actionClick" or whatever, and put this in it:

    btnDelete.enable(true);
    It has a line through it and then I run the program and it doesn't work. (thats the only way I know to utilize an ActionListener inside NetBeans ona button

  5. #4
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,320
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: jTable and jdbc

    Like now I can't figure out how to enable my btnDelete when someone clicks on the jTable
    Post an SSCCE that demonstrates the problem and it can be dealt with. If you are using a GUI builder and are more familiar with building things manually - then my opinion is (unless you have the time and patience) stick to what you are familiar with. I personally do not like GUI builders for the reason that they decouple the coder from the code...my .02

  6. #5
    Member
    Join Date
    Dec 2010
    Posts
    69
    My Mood
    Busy
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: jTable and jdbc

    I got the button issue figured out (had to use the .setEnabled function). I feel like the GUI Builder (NetBeans) allows me to build applications way faster then using hard coding. I never thought it'd be a huge difference until I actually used one, but like you said, it doesn kind of take the coder from the code in a way.
    Thank you again for all your help!

  7. #6
    Member
    Join Date
    Dec 2010
    Posts
    69
    My Mood
    Busy
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: jTable and jdbc

    Just one last question (i hope lol)

    What would be a good logically way of "refreshing" a jTable to reflect any changes made? I have an add and delete button and want the jTable to automatically reflect the changes made.
        private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {                                          
            int row = jTable1.getSelectedRow();
     
     
            String value = (String)jTable1.getValueAt(row, 0);
            try{
                String url = "jdbc:odbc:dts";
                String user = "";
                String password = "";
                Connection con = DriverManager.getConnection(url, user, password);
            if ( row >= 0 ){
     
            String delCust = "DELETE FROM Customer WHERE FirstName = ?";
            PreparedStatement ps = con.prepareStatement(delCust);
            ps.setString(1, value);
            ps.executeUpdate();
     
     
            }
           //delete from database given the value(s) to define the entry
                }
            catch(Exception e){
                lblConnect.setText("Failed to delete entry");
            }
     
        }
        private void btnSubmitActionPerformed(java.awt.event.ActionEvent evt) {                                          
               String FName = txtFirst.getText();
               String LName = txtLast.getText();
               String Addr = txtAddress.getText();
               String City = txtCity.getText();
               String State = txtState.getText();
               String Zip = txtZip.getText();
               String Phone = txtPhone.getText();
               String Email = txtEmail.getText();
                try{
     
                 new JdbcOdbcDriver();
                  String url = "jdbc:odbc:dts";
                  String user = "";
                  String password = "";
                  Connection con = DriverManager.getConnection(url, user, password);
                    String insertCustomer = "INSERT INTO Customer VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
                  PreparedStatement ps = con.prepareStatement(insertCustomer);
                  ps.setString(1, FName);
                  ps.setString(2, LName);
                  ps.setString(3, Addr);
                  ps.setString(4, City);
                  ps.setString(5, State);
                  ps.setString(6, Zip);
                  ps.setString(7, Phone);
                  ps.setString(8, Email);
                  int count = ps.executeUpdate();
            }
                 catch (Exception e){
                     JOptionPane.showMessageDialog(null,"Sorry could not add new customer.");
                 }
        }

    The only issue is, the Submit (add new) button is on a separate form and when I try to pass anything back to the original jFrame it gives me the whole non-static to static issue and i can't change the static value of the other one because NetBeans locks it to where I can't make changes to the "Private blah blah blah" stuff. (unless there is a way that im not aware of to change the static thing)

  8. #7
    Member
    Join Date
    Dec 2010
    Posts
    69
    My Mood
    Busy
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: jTable and jdbc

    I've tried even using:
     public void doDelete(){
        int i = 0;
        int r = 0;
     
        while (i < 600) {
            jTable1.remove(r);
     
            r++;i++;
        }
            doRefresh();
        }
        public void doRefresh(){
     
                try {
                String url = "jdbc:odbc:dts";
                String user = "";
                String password = "";
                Connection con = DriverManager.getConnection(url, user, password);
     
                String getCust = "SELECT *  FROM Customer";
                PreparedStatement ps = con.prepareStatement(getCust);
                ResultSet rs = ps.executeQuery();
     
                while (rs.next()){
                    String s = rs.getString(1);
                    jTable1.setValueAt(s, R, 0);
                    s = rs.getString(2);
                    jTable1.setValueAt(s, R, 1);
                    s = rs.getString(3);
                    jTable1.setValueAt(s, R, 2);
                    s = rs.getString(4);
                    jTable1.setValueAt(s, R, 3);
                    s = rs.getString(5);
                    jTable1.setValueAt(s, R, 4);
                    s = rs.getString(6);
                    jTable1.setValueAt(s, R, 5);
                    s = rs.getString(7);
                    jTable1.setValueAt(s, R, 6);
                    s = rs.getString(8);
                    jTable1.setValueAt(s, R, 7);
                    R++;
     
     
               }
     
            } catch (Exception e) {
                lblConnect.setText("Error in doRefresh()");
            }
    }
    and it doesn't work really.


    The "Delete" button will delete the info from the database properly (won't reflect changes to the jTable though) then you press the "Refresh" button and all of instead of the entire jTable being deleted and re-populated, it just appends the new database (minus the row you selected to be deleted)

Similar Threads

  1. jdbc
    By kundalikk in forum What's Wrong With My Code?
    Replies: 1
    Last Post: February 2nd, 2011, 04:38 AM
  2. sql/jdbc parser
    By anand.stk in forum Member Introductions
    Replies: 1
    Last Post: January 27th, 2011, 09:43 AM
  3. JDBC
    By Abdul Rasheed in forum JDBC & Databases
    Replies: 1
    Last Post: August 13th, 2010, 07:01 AM
  4. Help regarding JDBC connectivity in JSP
    By Lovable_Kumar in forum JDBC & Databases
    Replies: 0
    Last Post: May 30th, 2010, 11:53 AM
  5. Help with JDBC
    By michaelmel in forum JDBC & Databases
    Replies: 0
    Last Post: May 14th, 2010, 07:11 AM