Populating an existing vector from ResultSet

I want to populate a JTable's Table Model's Vector with data from a ResultSet. The code that I have
seen follows the general pattern of the code below, from "The JDBC:�Practical Guide for Java Programmers"
It creates a new Vector and fills the data in.
         public void presentResultSet(ResultSet rs)
     throws SQLException {
     Vector dataVector = new Vector();     //     ----------------------------- create an NEW Vector
     if (!rs.next())
         JOptionPane.showMessageDialog(null,"No records for customer");
     else {
         do {
          Vector rowVector = new Vector();
          rowVector.addElement(rs.getString("Title"));
          rowVector.addElement(rs.getString("Type"));
          dataVector.addElement(rowVector);
          } while (rs.next());
     Vector headVector = new Vector(2);
     headVector.addElement("Title");
     headVector.addElement("Type");
     dataTable = new JTable(dataVector, headVector);
     dataTableScrollPane.setViewportView(dataTable);
     I want to populate an existing vector which already exists, and has several methods attached to it.
Please look at the code below, and tell me if it is on the right track, or what changes need to be made.
     //     ------------------------------------------------- To populate an existing (tableModel) vector:
     int rows = 10;
     int cols = 10;
     Table2Model t2Model = new Table2Model();
     while (rs.next()) {
          for ( int r = 0; r < rows; r++ ) {                         
               for ( int c = 0; c < cols; c++ ) { // visibleColumns                    
                    ( ( Vector )t2Model.elementAt( r ) ).setElementAt( rs.getString( c+1 ), c );
     Many thanks in advance

Looks like you are

Similar Messages

  • Initializing Vector with ResultSet(TO SLOW!)

    Hi
    Im creating a JTable from two Vectors. I need to initialize
    the one vector from a resultset. This is way to slow for large result sets. Heres my loop:
    private Vector getData(int columns[]) throws Exception
         rows = new Vector(queue.count);
         while (res.next())     
             Vector newRow = new Vector(columns.length);
             for (int i = 0; i < columns.length;i++)  
               newRow.addElement(res.getString(columns));
    rows.addElement(newRow);
    return rows;
    Any Ideas to speed this up a bit.
    Thanks!

    private Vector getData(int columns[]) throws
    Exception
    rows = new Vector(queue.count);
    while (res.next())
    Vector newRow = new Vector(columns.length);
    for (int i = 0; i < columns.length;i++)
    newRow.addElement(res.getString(columns));
    rows.addElement(newRow);
    return rows;
    Any Ideas to speed this up a bit.
    Thanks!
    I tested your code using String[][] rows (instead of Vector rows) hoping using arrays will make it faster. But it did not. What really did improve the performance was declaring and alocating memory for String[][] rows before calling the function. That is to say, the most time is spent on rows = new String[ROWS][COLS]. If you your conditions allow you to use String[][] rows instead of Vector rows and allocate memory for String[][] rows before calling your method getData(), then, in my opinion, it will improve the performance.
    Cheers!

  • Can i count row from ResultSet ?

    I would like to count row from ResultSet for
    take it into my array object because i must know number of row before create array object.
    Example:
    ResultSet rset = stmt.executeQuery("select * from user ");
    /*i = amount of ResultSet*/
    User[] user = new User;
    int l=0;
    while (rset.next()){
    user[l] = new User();
    user.name = rset.getString(1);
    l++;

    Hi,
    As per my knowledge there is no method by which you can get the count of items in a resultset directly. You will have to loop through the reseltset and set a variable for count. In your specific case I would advise you to use a Vetor instead of an array so that you need not bother about the size.
    ResultSet rset = stmt.executeQuery("select * from user ");
    Vector user = new Vector();
    while (rset.next()){
    user.addElement(rset.getString(1));
    Now you will have a Vector that holds the user info. To retrieve the user info loop through the Vector.
    for (int i; i<user.size(); i++){
    userName = user.elementAt(i);
    Hope I was of some help.
    cheers!!!
    Nish

  • How can  I checkout an existing file from CVS without going through the wiz

    How can I checkout an existing file from CVS, that is not already in my local jdev, without going through the wizard and checkingout everything?

    You can't. AI doesn't produce .PLT files.

  • How do I add multiple songs to an existing playlist from the (no longer called) Library? Highlighting multiple songs and clicking the "Add to" button will only add the with the little arrow, not all the highlighted ones!

    How do I add multiple songs to an existing playlist from the (no longer called) Library? Highlighting multiple songs and clicking the "Add to" button will only add the one with the little arrow, not all the highlighted ones! I am using the "new" iTunes.

    For the moment there isn't a way for us end-users to control what is "matched" or "uploaded." That is purely a result of Apple's server-side algorithms.
    To re-add multiple songs at once simply highlight all the songs you want to re-add, then right-click (or Control+click) the list and choose "add to iCloud."

  • How can I copy my existing contacts from 1 Apple ID to a new one?

    How can I copy my existing contacts from 1 Apple ID to a new one?

    Click here and pick the option which best fits your situation. Rented movies can only be moved through the iPod and will not play on the new computer if any other method is used.
    (98456)

  • HT1688 does anyone know how to transfer the existing music from my itunes account that i had with an ipod to my iphone?  I had my last download on my laptop which crashed and now we have a new computer.  I had to download a new version of itunes.

    I had my itunes account on my laptop which has since crashed.   I had to buy a new computer and iinstall the new version of itunes.  It did not pull up any of my information with music library, etc.  Does anyone know how to transfer existing music from my itunes account for my ipod to my iphone?
    thanks

    Some of the information below has subsequently appeared in a document by turingtest2: Recovering your iTunes library from your iPod or iOS device - https://discussions.apple.com/docs/DOC-3991
    Your i-device was not designed for unique storage of your media. It is not a backup device and media transfer was designed for you maintaining a master copy of your media on a computer which is itself properly backed up against loss. Syncing is one way, computer to device, updating the device content to the content on the computer, not updating or restoring content on a computer. The exception is iTunes Store purchased content.
    iTunes Store: Transferring purchases from your iOS device or iPod to a computer - http://support.apple.com/kb/HT1848 - only media purchased from iTunes Store
    For transferring other items from an i-device to a computer you will have to use third party commercial software. Examples (check the web for others; this is not an exhaustive listing, nor do I have any idea if they are any good):
    - Senuti - http://www.fadingred.com/senuti/
    - Phoneview - http://www.ecamm.com/mac/phoneview/
    - MusicRescue - http://www.kennettnet.co.uk/products/musicrescue/
    - Sharepod (free) - http://download.cnet.com/SharePod/3000-2141_4-10794489.html?tag=mncol;2 - Windows
    - Snowfox/iMedia - http://www.mac-videoconverter.com/imedia-transfer-mac.html - Mac & PC
    - iexplorer (free) - http://www.macroplant.com/iexplorer/ - Mac&PC
    - Yamipod (free) - http://www.yamipod.com/main/modules/downloads/ - PC, Linux, Mac [Still updated for use on newer devices? No edits to site since 2010.]
    - 2010 Post by Zevoneer: iPod media recovery options - https://discussions.apple.com/message/11624224 - this is an older post and many of the links are also for old posts, so bear this in mind when reading them.
    Syncing to a "New" Computer or replacing a "crashed" Hard Drive - https://discussions.apple.com/docs/DOC-3141 - dates from 2008 and some outdated information now.
    Copying Content from your iPod to your Computer - The Definitive Guide - http://www.ilounge.com/index.php/articles/comments/copying-music-from-ipod-to-co mputer/ - Information about use in disk mode pertains only to older model iPods.
    Get Your Music Off of Your iPod - http://howto.wired.com/wiki/Get_Your_Music_Off_of_Your_iPod - I am not sure but this may only work with some models and not newer Touch, iPhone, or iPad.
    Additional information here https://discussions.apple.com/message/18324797

  • Can´t copy vector from Illustrator to Edge Animate

    In the newest version this should be a function, but nothing happens for me when I copy the object in Illustrator and try to paste it in Edge Animate. Any help?
    Another question would be why the filters are even among the tools in Edge when they don´t work on anything, neither vectors not photos.. and also, texts often don´t end up correct in the preview. Seriously, I work as a graphic news designer professionally and pay money for your products. This is not OK.

    That´s how you went about it in the older versions. In the New 2014 Edge you´re supposed to be able to just ctrl+C a vector from Illustrator and ctrl-V it in Edge. That´s one of the big new features. But nothing happens for me and there doesn´t seem to be any one else who experiences this problem since I haven´t found anything on it when googling.
    Thanks anyway.

  • How can I display data from ResultSet to a component like jLable and JTable

    hi there
    My code as shown below
    boolean fillTable(int type){
            try{
                //model.setRowCount(0);
                if(type == 1){
                    System.out.println("line 1");
                    model = new DefaultTableModel(new Object [][] {   },
                            new String[] { "\u1200 Code", "Description" });
                    System.out.println("line 2");
                    while(lookup.rs2.next()){
                        System.out.println("line in while");
                        model.addRow(new String[] { lookup.rs2.getString("code"),
                            "\u1201 " + lookup.rs2.getString("amdescription")});
                          //System.out.println("While : " + lookup.rs2.getString("code") + " " +
                            //      lookup.rs2.getString("amdescription"));
                    lookup.rs2.last();
                    String str;
                    str =  new String (lookup.rs2.getString("amdescription"));
                    jLabel2.setText(str);
                    System.out.println("line 3");
                    tblLookup.setModel(model);
                    System.out.println("line 4");
                else if(type == 2){
                    System.out.println("line else if 1");
            }catch(Exception ex)    {
                System.out.println("Exception @ MilLookupDisplay fillTable : " + ex.getMessage());
                return false;
            return true;
        }I can read from access db and put the resultset on rs2 , it works fine
    my problem is when I try to display the data ( which is amharic unicode character ) on jTable and jLabel as shown it displays '???'
    besides I have checked the font by giving unicode like '\u1200' on both component displays it well
    so is there something to do before trying to display unicode characters from resultSet
    please I ' m waiting
    thanks a lot

    http://forum.java.sun.com/thread.jspa?threadID=5153938

  • Heap space error while creating XML document from Resultset

    I am getting Heap space error while creating XML document from Resultset.
    It was working fine from small result set object but when the size of resultset was more than 25,000, heap space error
    I am already using -Xms32m -Xmx1024m
    Is there a way to directly write to xml file from resultset instead of creating the whole document first and then writing it to file? Code examples please?
    here is my code:
    stmt = conn.prepareStatement(sql);
    result = stmt.executeQuery();
    result.setFetchSize(999);
    Document doc = JDBCUtil.toDocument(result, Application.BANK_ID, interfaceType, Application.VERSION);
    JDBCUtil.write(doc, fileName);
    public static Document toDocument(ResultSet rs, String bankId, String interfaceFileType, String version)
        throws ParserConfigurationException, SQLException {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.newDocument();
            Element results = doc.createElement("sims");
            results.setAttribute("bank", bankId);
            results.setAttribute("record_type", "HEADER");
            results.setAttribute("file_type", interfaceFileType);
            results.setAttribute("version", version);
            doc.appendChild(results);
            ResultSetMetaData rsmd = rs.getMetaData();
            int colCount = rsmd.getColumnCount();
            String columnName="";
            Object value;
            while (rs.next()) {
                Element row = doc.createElement("rec");
                results.appendChild(row);
                for (int i = 1; i <= colCount; i++) {
                    columnName = rsmd.getColumnLabel(i);
                    value = rs.getObject(i);
                    Element node = doc.createElement(columnName);
                    if(value != null)
                        node.appendChild(doc.createTextNode(value.toString()));
                    else
                        node.appendChild(doc.createTextNode(""));
                    row.appendChild(node);
            return doc;
    public static void write(Document document, String filename) {
            //long start = System.currentTimeMillis();
            // lets write to a file
            OutputFormat format = new OutputFormat(document); // Serialize DOM
            format.setIndent(2);
            format.setLineSeparator(System.getProperty("line.separator"));
            format.setLineWidth(80);
            try {
                FileWriter writer = new FileWriter(filename);
                BufferedWriter buf = new BufferedWriter(writer);
                XMLSerializer FileSerial = new XMLSerializer(writer, format);
                FileSerial.asDOMSerializer(); // As a DOM Serializer
                FileSerial.serialize(document);
                writer.close();
            } catch (IOException ioe) {
                ioe.printStackTrace();
            //long end = System.currentTimeMillis();
            //System.err.println("W3C File write time :" + (end - start) + "  " + filename);
        }

    you can increase your heap size..... try setting this as your environment variable.....
    variable: JAVA_OPTS
    value: -Xms512m -Xmx1024m -XX:PermSize=256m -XX:MaxPermSize=512m

  • How do I copy existing songs from Computer Hard Drive to IPOD 30GB

    How do I copy existing songs from Computer Hard Drive to IPOD 30GB? I am slightly learning disabled and have been unable to figure out how to add and or update. Thnaks

    If the songs are in iTunes and the iPod is set to sync automatically, the songs should already be on the iPod; if they aren't, follow the instructions in this article and post back with any error messages.
    If the iPod is set to sync manually, drag the songs onto the iPod in the iTunes source list.
    (21058)

  • How to update (add new data in different tab) existing table from Excel

    i've an existing table, for instance User Profile table, it consists of few tab in the table which contains different data... recently i've added new tab to the existing table and i would like to upload a particular data for this new tab... is there any way to upload (insert new data for the tab on existing data) this particular data into the existing table from Excel file?
    could it be done by using lsmw?
    Edited by: Yeong Kang Liew on Apr 5, 2010 4:35 AM

    Check HELP on MODIFY & UPDATE statements.

  • Javascript to create vector from image and save as eps

    Hi,
    I started writing a script which open all images in a folder and i need to turn those into vectors.
    How do i write the following in JavaScript:
    Open the JPG file
    Select the image layer/object
    Create a vector from the image using the Image Trace for high fidelity 
    Reduce the new vector objec size by %50.
    save as eps
    any help with any of the stages would be very helpful.
    thank you

    PERFECT!!!!!!
    This is exactly what I was going to build.  No need to create when it is already done.
    Thank you very much.
    -Mike

  • Can BPm pick up existing process from ECC without human intervention

    Hi
    Is there any way BPM can read/pick the existing process from ECC system (may be solution manager workflow) and model the same.
    Just trying to make sure from experts that it is not possible before replying client.
    Lavanya
    Edited by: Lavanya Sambaraju on Nov 19, 2010 8:23 AM

    Hi Anil
    Yes, we wanted to know if the process/workflow mainateined in ECC or solution manager can be dyna,mically picked up by BPM.
    And your solution -  "Currently BPM can talk to any other system through web services.If you can expose any functionality as web service in solution manager, you can call that from BPM"
    how to implement this from solution manger?
    All we know was to expose the BAPI/RFC's functionalities  as web services from ECC and consume in BPM tasks or directly call these BApis in to BPM tasks.
    Could you please share with us.
    Thank you.

  • How to edit an existing vector in perspektive tool

    Hello,
    as the topic says.
    How to edit an existing vector in perspektive tool
    Got an Domino Stone Vector and want to put in another perspective and dont know how!?
    Thx in advance for help

    Before putting complex art in perspective grid, ALWAYS create a symbol first.
    You can only rotate perspective layers (and the art) around the vanishing points. You cannot change perspective or move the vanishing points (at least not if you want to artwork to adapt to it).

Maybe you are looking for

  • I'm trying to download Adobe Creative Cloud and getting (Error code: 50)

    What do I need to do about this error code: 50?

  • After 8.3 update my keyboard is not working at all?

    After the update 8.3 I am no longer able to use my keyboard?

  • Trivia

    Explain: class test      public static void main(String args[])           String file = "-134343";           System.out.println(file.substring(0,2));           if(file.substring(0,2) == "-1")           System.out.println("yes");           String file

  • Files locked!!!!!

    I transfered some files from a drive to another drive. The folders are not locked but the wave files inside each folder are locked. I can unlock the wave files one at a time or by opening a folder and then selecting all of the wave files in that fold

  • The New BT Yahoo Mail is terrible (email heading:"...

    I received an email about a week ago asking me to upgrade from BT Yahoo Mail Beta to the newer version.  The title of the email was "We're Upgrading BT Yahoo!  Mail".  I was happy with the switch from Classic to Beta because it enabled me to use the