Moving a ResultSet into a JTable, cheaply and efficiently.

Hi,
This may be something interesting for the more advanced Java programmers.
I've recently run into an issue, with moving a ResultSet into a JTable. Now, this may seem simple, and believe me it is, but, all the ways I have seen it done, and tried, just don't suite my need.
DBSql dbsql = new DBSql(); // My database handler class
tableResults.setModel(new javax.swing.table.DefaultTableModel(dbsql.execute(script), dbsql.getColumns()));
* Queries the DataBase and populates
* the values into a two-dimensional object array
* @param SqlQry
* @return Object[][]
public Object[][] execute(String SqlQry) throws SQLException {
Object[][] obj = null;
select = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet rs = select.executeQuery(SqlQry);
rsmd = rs.getMetaData();
try {
if (rs.next()) {
boolean found = true;
rs.last();
recordCount = rs.getRow();
rs.first();
obj = new Object[recordCount][rsmd.getColumnCount()];
int i = 0;
while (found) {
for (int j = 0; j < rsmd.getColumnCount(); j++) {
obj[i][j] = rsmd.getColumnType(j + 1) != Constants.TYPE_INTEGER ? rs.getString(j + 1) : rs.getInt(j + 1);
i++;
found = rs.next();
} else {
recordCount = 0;
return null;
} catch(OutOfMemoryError oome) {
System.gc();
throw new SQLException("Out Of Memory");
if(rs != null) rs.close();
return obj;
The application I have created is used to connect to any database I want. I have tested it with JavaDB, Microsoft Access, and DB2. The problem is, most DB2's have tables with many records and columns, while most new Relational Databases, have small tables with few records. This code works fantastic with a couple thousand records, with very few columns. But, doesn't cut it when it comes to 50000 records or more. For, instance I queried a DB2 table that has 34000 records and 117 columns ("select * from table"), it doesn't take too long, but it uses way too much memory. If I run that query the application resources 298mb, then when I run it again, it uses a little more and throws an OutOfMemoryError.
The second issue I have is, I queried another table that has 147000 records and selected 4 columns. No OutOfMemoryError this time - 70mb resourcing - but, the application did take at least 20 minutes to collect those records.
I have tried using the Vector<Vector<String>> type into the JTable, but, frankly that's just asking for an OutOfMemoryError.
I have tried creating my own custom table model, with a created data object.
I have tried inserting rows into a table model in the method itself and returning the table model.
Eg.
while (found) {
Object[] obj = new Object[rsmd.getColumnCount()];
for (int j = 0; j < rsmd.getColumnCount(); j++) {
obj[j] = rsmd.getColumnType(j + 1) != Constants.TYPE_INTEGER ? rs.getString(j + 1) : rs.getInt(j + 1);
tablemodel.insertRow(obj);
found = rs.next();
^I think you can use a vector for this too.
So far, nothing has solved my problem.
One thing I have not tried however, is a different table component for this kind of thing.
I'm basically looking for, a method of doing this, with less overhead and quicker table population.
Any Ideas?
Regards,
That_Gui

Thanks for the reply.
"1) Swing related questions should be posted in the Swing forum."
Apologies, I was caught between swing and essentials, as it seemed to me as, more of a "better ways to do things" kind of question.
"Also, the approach you are using requires two copies of the data, one in the ResultSet and one in the TableModel."
I understand that transferring a ResultSet into an Object Array may probably be resource intensive, my delphi colleague made mention of that to me, not too long ago. That is why I'm trying to transfer the ResultSet directly into the table. That is why I used the ListTableModel, which also uses a lot of memory, I have looked at that - I had forgotten to mention that.
"I have seen approaches where you try to only read a specific number of records. Then as you scroll additional records are read as needed. I can't point you to any specific solution though."
Using an approach of reading the data as you scroll, sounds great, but also sounds like unnecessary work for the program to do, just like this Object/Vector story. In RPG, if you are working with subfiles (like a JTable), you will display 10 records at a time, and if the user hits the Page Down button you will display the next 10, that is how I'm understanding it.
"I rarely use DefaultTableModel, creating your own model from AbstractTableModel is a lot more flexible when it comes to how you organise your storage, and it's pretty simple once you get the hang of it."
This is the dream, I just need to design one that works as I need it.
"You'd do a select count(*) on your query first to get the total rows expected. Of course one of the problems is that the databased table may change after you've retrieved the length or the items."
Unfortunately, this is not an option for me, it wont work for what I need.
I'm going to give the ResultSetTableModel a go - which I think it is actually similar to the ListTableModel - and I will get back to you.

Similar Messages

  • Turning a resultset into a JTable

    How can i covert a resultset into a table?
    1. I created a resultset from database data.
    2. I scanned through the resultset to determine how many items i need to extract.
    3. I created an array of the same size as the number of items i need to extract.
    4. Now when i use the getString() commands it tells me that their is no data!
    Help!

    Your ResultSet will not be scrollable so once you've got to the end you can't go back to get the data. You could create a scrollable result set but there's no need if you use another data structure to store your data. You could use a Vector for example and as you will see a JTable has a constructor (Vector v1, Vector v2) where v1 contains the column names and v2 is in fact a Vector of Vectors containing the row data.
    To get the columns names, assuming you have a ResultSet object, rs:
    ResultSetMetaData rsmd = rs.getMetaData();
    Vector columns = new Vector();
    // check these ResultSetMetaData methods in API as I don't have it to hand right now - I think I have them right!
    for (int counter = 0; counter < rsmd.getColumnCount(); ++ counter)
    String name = rsmd.getColumnName(counter);
    v.add(counter);
    }Extract the data from the rows into a Vector of Vectors.

  • Insert a mysql resultset to a jTable

    Hi! I have a database which i can connect to and get information from, but i can't figure out how to insert my resultset into my jTable from two different classes, I found an good exaple on the web but i dont know how to split up the code. I work with the GUI editor in NEtbeans 6.8 since i'm most familiar with it.
    I have bound an jButton (that lies in Class A) that will call an method in Class B which will update the jTable.
    The action event code
    //Creates object "b" from the class ClassB
    ClassB b = new ClassB();
            try {
            //Call method showall in ClassB
            b.showall();
            } catch (ClassNotFoundException ex) {
    System.out.println("Class not found);
    {code}
    And here is the method "showall"
    {code}
            String sql = "my sql query";
            ResultSet rs = dc.query(sql);
            Object[] rows;
            while (rs.next()) {
             //add the values to the temporary row
            rows = new Object[]{rs.getInt(0), rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(4)};
            // add the temp row to the table
            // Startup is the name of my mainclass wich i have the jTable in (named "table")
          Startup.table.setValueAt(rows, 1, 1);
    {code}
    This is the example i found
    {code}
    class MySQLTable
      private static Connection con = null;
      private static String URL = "jdbc:mysql://localhost:3306";
      private static String driver = "com.mysql.jdbc.Driver";
      private static String user = "root";
      private static String pass = "";
       * Main aplication entry point
       * @param args
       * @throws SQLException
      public static void main(String[] args) throws SQLException
        // a MySQL statement
        Statement stmt;
        // a MySQL query
        String query;
        // the results from a MySQL query
        ResultSet rs;
        // 2 dimension array to hold table contents
        // it holds temp values for now
        Object rowData[][] = {{"Row1-Column1", "Row1-Column2", "Row1-Column3"}};
        // array to hold column names
        Object columnNames[] = {"ID", "User", "Password"};
        // create a table model and table based on it
        DefaultTableModel mTableModel = new DefaultTableModel(rowData, columnNames);
        JTable table = new JTable(mTableModel);
        // try and connect to the database
        try {
          Class.forName(driver).newInstance();
          con = DriverManager.getConnection(URL, user,pass);
        } catch (Exception e) {
          System.err.println("Exception: " + e.getMessage());
        // run the desired query
        query = "SELECT ID, User, Password FROM users.normal";
        // make a statement with the server
        stmt = con.createStatement();
        // execute the query and return the result
        rs = stmt.executeQuery(query);
        // create the gui
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JScrollPane scrollPane = new JScrollPane(table);
        frame.add(scrollPane, BorderLayout.CENTER);
        frame.setSize(300, 150);
        frame.setVisible(true);
        // remove the temp row
        mTableModel.removeRow(0);
        // create a temporary object array to hold the result for each row
        Object[] rows;
        // for each row returned
        while (rs.next()) {
          // add the values to the temporary row
          rows = new Object[]{rs.getString(1), rs.getString(2), rs.getString(3)};
          // add the temp row to the table
          mTableModel.addRow(rows);
      private MySQLTable()
    {code}
    I would appreciate some help with this :)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    I am now close to my goal, no errors when i run my application but nothing happens to the jTable
    Here is the code for the method
        public void gettableinfo() throws ClassNotFoundException, SQLException{
            String sql = "sql query";
            ResultSet rs = DatabaseConnection.query(sql);
            Object[] rows;
            Startup.mTableModel.removeRow(0);
            while (rs.next()) {
            //add the values to the temporary row
            System.out.println(rs.getRow());
            rows = new Object[]{rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getString(5)};
            // add the temp row to the table
            Startup.mTableModel.addRow(rows);
        }rs.getrow(); finds 12 rows, as i have in my database. but it dosent add the result to the table
    the code for the jTable:
    static Object rowData[][] = {{"Row1-Column1", "Row1-Column2", "Row1-Column3","Row1-Column4","Row1-Column5"}};
        // array to hold column names
      static Object columnNames[] = {"ID", "Name", "Info", "Type", "Material"};
      public static DefaultTableModel mTableModel = new DefaultTableModel(rowData, columnNames);since i'm using the netbeans GUI editor it makes it a little more complicated. I've set the Jtable as public static and the "table = new JTable(mTableModel);" as followed in the example. It still dont work.
    Any ideas?

  • Query resultset to xml using java and XML schema

    Hi,
    I query data using JDBC and I want to store it to an XML file which has a well defined XML schema. I searched a lot in the forum but did not find an answer. Please guide me to create this program.
    I have managed to use JDBC to get result set but I do not know how to export is to XML using XSD and Java.
    Please help.
    Regards,
    Ravi

    I have managed to use JDBC to get result set but I do
    not know how to export is to XML using XSD and Java.Export using XSD? Schemas are for validation.
    Iterate through the result set, and build up the XML stream by creating an entry for each row.
    Another way to do it is to load the ResultSet into a Java object and serialize that to XML using something like XStream.
    %

  • Hi there i have just moved into a new pad and the internet is running on a proxy server how do i get my ATV2 to work ?

    Hi there i have just moved into a new pad and the internet is running on a proxy server how do i get my ATV2 to work ?

    Bladerider900 wrote:
    Thanks ...
    You're Welcome.

  • I have a Macbook Pro (2013) OS 10.8.1.  Moved into a university house and need to use ethernet cable. Bought the Thunderbold connection but when I try to use the ethernet with it a webpage comes up saying Wireless Setup? No idea what to do.

    I have a Macbook Pro (2013) OS 10.8.1.  Moved into a university house and need to use ethernet cable. Bought the Thunderbold connection but when I try to use the ethernet with it a webpage comes up saying Wireless Setup and Router Setup? I have previously used ethernets in similar situations and never had to input information like this?

    I have tried to turn of the wi-fi but that doesn't work either. I think it could be a something to do with the internet provider because virginmedia comes up on the webpage. This is what comes up:
    Wireless Setup
    WGR614V9
    V1.0.11_1.0.1VGUK
    Wireless Setup
    Name (SSID):
    Security Passphrase (WPA-PSK):
    (8-63 characters)
    Channel:
                       01                   06                   11                
    Router Setup
    Router Password:
    (8-63 characters)
    any ideas?!?

  • I was organizing my photos into albums. then deleting them from my Camera roll. Then I went into MY Photo Stream and started deleting the pics I had moved to albums;Come to find out I deleted all pic from everywhere!!  Would the iCloud still have them sav

    I was organizing my photos into albums. then deleting them from my Camera roll. Then I went into MY Photo Stream and started deleting the pics I had moved to albums;Come to find out I deleted all pic from everywhere!!  Would the iCloud still have them saved

    First of all, you should always save you photos on computer like any other digital camera.
    Backup on iCloud or iTunes only backup your Camera Roll. The other photos should be already on the computer.
    Note: Photos are not saved in iTunes, it's only a conduit between your iPhone and your photo managing software on computer.
    What computer do you have?

  • I recently moved into a new apartment and I can connect with the internet by direct connection to the cable/internet modem.  But when I connect my Airport Express, it just blinks with a yellow light and I cannot connect via WiFi.  Any suggestions?

    I recently moved into a new apartment and can connect with the internet by direct attachment to the cable/internet modem.  But when I try to connect the modem to my Airport Express, the Airport just blinks yellow and I cannot get my WiFi.  Any suggestions?

    Try this User Tip from forum expert Tesserax:
                     AirPort - Complete Power Recycle

  • Accidentally Moved Blackberry Messenger Into Wrong Folder - How Do I Move Back?

    Hi Guys, I accidentally moved Blackberry Messenger into the SMS and MMS Folder instead of just moving the icon around.
    Please advise how I move it out of this folder and back to the Home Screen?
    Thanks,
    PETER

    Scroll to the icon > press the Menu key > Move to Folder > and choose which one you would like it put in, Home Screen, if that is where you want it.
    1. If any post helps you please click the below the post(s) that helped you.
    2. Please resolve your thread by marking the post "Solution?" which solved it for you!
    3. Install free BlackBerry Protect today for backups of contacts and data.
    4. Guide to Unlocking your BlackBerry & Unlock Codes
    Join our BBM Channels (Beta)
    BlackBerry Support Forums Channel
    PIN: C0001B7B4   Display/Scan Bar Code
    Knowledge Base Updates
    PIN: C0005A9AA   Display/Scan Bar Code

  • I can't be the only person who has this problem - when a month ends on a Saturday I can't drag events into the next month and instead have to cut and paste - a real pain in the butt. I thought there was something called "scroll" but I can't find that

    I can't be the only person who has this problem with iCal- when a month ends on a Saturday I can't drag events into the next month and instead have to cut and paste - a real pain in the butt. I thought there was something called "scroll" but I can't find that.

    Yeah that works, but, it involves a click on the event, a click on edit, a click on the date, keystrokes, plus, since you can't see the next month you have to have a calendar in front of you so as to put it to the right date. It's easier just to cut it and advance the month and paste it, once you are in the right month you can move it around helter skelter willy nilly no problems. Although now that you mention it I will try it, maybe it is easier than cut and paste as I don't really care about the date, as long as it gets moved into the right month I can drag it around all I want.

  • I have moved from the UK to New Zealand and Itunes will not accept my new Zealand bank details, as a result nothing will work on my phone and I cant access emails!

    I have moved from the UK to New Zealand and Itunes will not accept my new Zealand bank details, I am trying to change my details on the Iphone 4s

    Do you have a new Apple ID to use in NZ? If not open iTunes Store. Log out of your old Apple ID, then try to login. Select Create Apple ID from the dialog that appears. Make a new Apple ID for NZ with a NZ email address. Once that is approved and verified, log into the iTunes Store with the new Apple ID. This should fix all other issues.
    Change iTunes Store Country on an iDevice
    1. Tap Settings;
    2. Tap iTunes & App Stores;
    3. Tap View Apple ID;
    4. Enter your user name and password;
    5. Tap Country/Region;
    6. Tap Change Country/Region;
    7. Select the region where you will be located;
    8. Tap Done.
    Also, see How to Change Your iTunes Store Account Location | eHow.com.

  • How can I add new row/column into existing jTable?

    Hi add!
    Can you help me how can I add new row/column into existing jTable?
    Tnx in adv!

    e.g
    Create two buttons inside the Table ( "Add New Row" ) and ("Add new Column")
    their handlers are:
    add new row:
    //i supose u already have
    DefaultTabelModel tablemodel = new DefaultTableModel(rowdata, columnNames);
    //and   
       JTabel jtable = new JTable(tablemodel);
    // Handler (row)
    jbtAddRow.addActionListener(new ActionListener(){
       public void actionPerformed(ActionEvent e) {
          if(jtable.getSelectedRow() >= 0 )
              tablemodel.insertRow(jtable.getSelectedRow(), new java.util.Vector());  
           else  
                tablemodel.addRow(new java.util.Vector());
        });to add new columns its the same but inside actionPerformed method:
    ask for e.g "Whats the name for the new column"
    then,
       tablemodel.addColumn(nameOfColumn, new java.util.Vector());   Joao
    Message was edited by:
    Java__Estudante

  • Moving sequence back into ultrabeat

    Hello. Admittedly, I am kind of a newbie with Logic so sorry if this is a simple question. I couldn't find the answer searching.
    I created a sequence in ultrabeat and moved the pattern into the main logic sequence window. I closed ultrabeat and would like to re-open the sequence in ultrabeat to edit it.
    It does not appear to open back up with the sequence loaded. Is there a way to re-open the sequence in ultrabeat to edit it?
    Thanks!

    can re-record a segment from the arrange window into ultrabeat

  • Loading the Contents of a file into a JTable

    I am trying to load the content of a delimited (tab, comma, etc), into a JTable. The code is very simple and works for the most part. Here is some of it:
                   List tableRows = new ArrayList();
                   String lineItem = "";
                   InputStream in = new FileInputStream(fName);
                   InputStreamReader isr = new InputStreamReader(in);               
              BufferedReader br = new BufferedReader(isr);
         while((lineItem = br.readLine()) != null)
                        if(x == MAX)
                             break;
                        java.util.List rowData = new ArrayList();
                        StringTokenizer st = new StringTokenizer(lineItem, "\t");
                        while(st.hasMoreElements())
                             rowData.add(st.nextToken());
                        tableRows.add(rowData);     
                        x++;
    Basically, tableRows, ends up to be a List of Lists which I later use to populate the Object[][] for the JTable rows. This works perfect!
    My problem has to do with the tokenizer. In some situations, values in a line that is read contains "". For example an line read (quotes are showed only to distinquish values in the line):
    "item1", "item2", " ", "item4", " ", "item6", "item7"
    The tokenizer does not capture the " ". So instead of 7 tokens, it only sees 5.
    My question is, can someone tell me a better approach for tokenizing the string so that it captures everything?
    Thanks in advance,
    Augustine

    I am trying to load the content of a delimited (tab, comma, etc), into a JTable. The code is very simple and works for the most part. Here is some of it:
                   List tableRows = new ArrayList();
                   String lineItem = "";
                   InputStream in = new FileInputStream(fName);
                   InputStreamReader isr = new InputStreamReader(in);               
              BufferedReader br = new BufferedReader(isr);
         while((lineItem = br.readLine()) != null)
                        if(x == MAX)
                             break;
                        java.util.List rowData = new ArrayList();
                        StringTokenizer st = new StringTokenizer(lineItem, "\t");
                        while(st.hasMoreElements())
                             rowData.add(st.nextToken());
                        tableRows.add(rowData);     
                        x++;
    Basically, tableRows, ends up to be a List of Lists which I later use to populate the Object[][] for the JTable rows. This works perfect!
    My problem has to do with the tokenizer. In some situations, values in a line that is read contains "". For example an line read (quotes are showed only to distinquish values in the line):
    "item1", "item2", " ", "item4", " ", "item6", "item7"
    The tokenizer does not capture the " ". So instead of 7 tokens, it only sees 5.
    My question is, can someone tell me a better approach for tokenizing the string so that it captures everything?
    Thanks in advance,
    Augustine

  • Disable JTable draggable? // reimporting into a JTable?

    How do I disable the ability to drag and drop the colons of a JTable?
    I am making a database where I am importing from a file (to view, but not edit it). How can I reimport the file after I have imported it into the JTable?
    This is my code at the moment.
        public void reload()
            ArrayList<String> ve = new ArrayList<String>(9); // imports the file into an ArrayList of lines
            try
                BufferedReader reader = new BufferedReader(new FileReader(source));
                String line = null;
                while ((line = reader.readLine()) != null)
                    ve.add(line);
                reader.close();
            catch (IOException e)
                System.out.println("Error reading file.");
            ve.trimToSize();
            String [][] data = new String[ve.size()/9][];
            for(int i = 0; i < data.length; i++)
                data[i] = new String[9];
                String name = ve.get(9*i);
                data[0] = name;
    String mobile = ve.get(9*i+1);
    data[i][1] = mobile;
    String dest = ve.get(9*i+2);
    data[i][2] = dest;
    String tranOut = ve.get(9*i+3);
    data[i][3] = tranOut;
    String tranIn = ve.get(9*i+4);
    data[i][4] = tranIn;
    String adult = ve.get(9*i+5);
    data[i][5] = adult;
    String number = ve.get(9*i+6);
    data[i][6] = number;
    String dep = ve.get(9*i+7);
    data[i][7] = dep;
    String arr = ve.get(9*i+8);
    data[i][8] = arr;
    sort(data); // run quickSort
    table = new JTable(data, columnNames);
    scrollPane = new JScrollPane(table);
    }It works the first time it is run, but not when I try to call it later (from the menus).                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    In future, Swing questions should be asked in the [Swing Forum.|http://forums.sun.com/forum.jspa?forumID=57]
    The header row of a JTable is really an instance of JTableHeader . Take a look at the API and see if there are any methods that would be of use. (Hint: there are!)

Maybe you are looking for

  • Acrobat Pro 7.1 in Win7 (64bit) Printer Settings must be confirmed twice

    I have an customer which I just delievered 3 new Workstations with Windows 7 (64 bit) to. Each one is running Adobe Acrobat 7.1 Professional. The issue is that each time when they want to print, and they want to customize printer device configuration

  • Hyperlinks to PDF files with Excel XP will not open on Acrobat

    Hi all; I am having an issue with Acrobat Reader X. I am using Windows 7 x64 Pro, with Acrobat Reader X, and MS Office XP and try as I might, I cannot create an Hyperlink to a PDF document.  Excel says that "there is no program registered to open thi

  • Outbound Queue stacking up for old destination

    Hi Gurus, I am implementing APO in a client and since the native integration (CIF) uses the same RFC structure as BW I need to keep an eye on BW processes as well. The problem here is that they´ve migrated to BW7, killing the old 3.5 but leaving the

  • Error in displaying PDF file in webdynpro application

    Hi Experts, I am trying to display one pdf file using webdynpro abap using MIME. While executing the application i am getting an error in the browser: " File doesnot begin with '%PDF-' " Please help me to proceed. Regards, Arun.

  • Launching AIR application(MAC)

    <MAC ONLY> I created a 'hello world' AIR app. using Flex builder 3 and I click the debug button and the somehow helloWorld-app.xml launches in Dreamweaver. Does anyone know how to fix this? all i'm trying to do is create a simple AIR app. and click t