ResultSet into vector

Posted on 2005-03-09
Medium Priority
Last Modified: 2012-06-21
In this code below, i am trying to store all the the values in resultSet into a vector.
But for some reason only the first data in the tables i am selecting from are being
stored( I know this by printing the items in the vectors.)
Why this behavior?

============ CODE =================
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import javax.swing.*;
import java.util.*;

 * @author  Agbeko Komla
public class Refresh implements ActionListener

    private StudentPanel studentFields;
    private Connection connection ;
    /** Creates a new instance of Refresh */
    public Refresh(Connection con, StudentPanel s)
        connection = con;
        studentFields = s;
    public void actionPerformed(ActionEvent e)
        Statement s = null;
        ResultSet lastRs = null;
        ResultSet firstRs  = null;
        Vector lastNames = new Vector();
        Vector firstNames = new Vector();
                s = connection.createStatement();
                lastRs = s.executeQuery("SELECT [Last Name] FROM Student");
                if( lastRs.next() )
                lastNames =  getNextRow(lastRs, lastRs.getMetaData()) ;

              s = connection.createStatement();
              firstRs = s.executeQuery("SELECT [First Name] FROM Student");
              if( firstRs.next() )
               firstNames = getNextRow(firstRs, firstRs.getMetaData()) ;
                    // System.out.println("first: " + firstRs.getString(1) );

       studentFields.initVectorOfNames(lastNames, firstNames);
      // firstRs.close();
      System.out.println( printaList(lastNames) );
      System.out.println( printaList(firstNames) );
       catch (SQLException sqlex)
    public Vector getNextRow(ResultSet rs, ResultSetMetaData meta)
   throws SQLException
    Vector currentRow = new Vector();
    for(int i = 1; i <= meta.getColumnCount(); i++)
        switch(meta.getColumnType(i) )
            case Types.DOUBLE:
                double x = rs.getDouble(i);
                int u = (int)x;
                currentRow.addElement( u + "" );
            case Types.VARCHAR:
            case Types.LONGVARCHAR:
                currentRow.addElement(rs.getString(i) );
            case Types.INTEGER:
                currentRow.addElement( new Long( rs.getLong( i )) );
           case Types.DATE:
                currentRow.addElement( rs.getDate( i ) );
            case Types.TIME:
                 currentRow.addElement(rs.getTime( i ) );
        case Types.TIMESTAMP:
             currentRow.addElement(rs.getTimestamp( i ) );
        case Types.OTHER:
        case Types.JAVA_OBJECT:
             currentRow.addElement(rs.getObject( i ) );
        return currentRow;
      public String printaList(java.util.List l)
        String s= "";
        for(int i = 0; i < l.size(); i++)
        s +=  (String)l.get(i)+ " ";
        return s;
Question by:komlaaa
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions

Accepted Solution

Leviter earned 1000 total points
ID: 13503702
Okay, here goes.......

You do this:

                lastRs = s.executeQuery("SELECT [Last Name] FROM Student");
                if( lastRs.next() )
                lastNames =  getNextRow(lastRs, lastRs.getMetaData()) ;

So lastRs will contain a resultset with multiple records. You however do not loop over all the records, but check if there is one and if so, you get that one. Then you do nothing anymore with the lastRS. The same is done for the firstRs.

Another thing is, that you return a new Vector each time you call the getNextRow method and assign it to the variable lastNames (in this case). So even if you loop through all the records in the resultset, you will only get one.

What you should do, is at least loop through the resultset.... something like this (not tested):

                lastRs = s.executeQuery("SELECT [Last Name] FROM Student");

                while (lastRs.next()) {
                      Vector lastName =  getNextRow(lastRs, lastRs.getMetaData()) ;

The method getNextRow returns a new Vector containing multiple elements (if the metadata contains more then one element). So what you get in the above example is a Vector containing Vectors.

This would be the 'quick' way to get it working.....

There is however a 'nicer' way. You should get the first and last name with only one query:

               select [last name], [first name] from student

Loop over this and create a new class called something like 'Student' which has two members named 'lastName' and 'firstName'. Loop over the resultset and create a new instance of the 'Student' class for each record and set the members. This instance should be added to a Vector of students. That way you get a more clear and better insight....

Look at this (incomplete example):

                s = connection.createStatement();
                rs = s.executeQuery("SELECT [Last Name], [First Name] FROM Student");

               Vector students = new Vector();
                while( rs.next() ) {
                           Student student = new Student();

                           student.setLastName(rs.getString("Last Name"));
                           student.setFirstName(rs.getString("First Name"));


               System.out.println( printaList(students) );
       catch (SQLException sqlex)
LVL 86

Expert Comment

ID: 13505317
You can use this convenience method:

 public TableModel resultSetToTableModel(ResultSet rs) {
          try {
               ResultSetMetaData metaData = rs.getMetaData();
               int numberOfColumns = metaData.getColumnCount();
               Vector columnNames = new Vector();
               // Get the column names
               for (int column = 0; column < numberOfColumns; column++) {
                    columnNames.addElement(metaData.getColumnLabel(column + 1));
               // Get all rows.
               Vector rows = new Vector();
               while (rs.next()) {
                    Vector newRow = new Vector();
                    for (int i = 1; i <= numberOfColumns; i++) {
               return new DefaultTableModel(rows, columnNames);
          catch (Exception e) {
               return null;

Featured Post

On Demand Webinar: Networking for the Cloud Era

Ready to improve network connectivity? Watch this webinar to learn how SD-WANs and a one-click instant connect tool can boost provisions, deployment, and management of your cloud connection.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
How to fix incompatible JVM issue while installing Eclipse While installing Eclipse in windows, got one error like above and unable to proceed with the installation. This video describes how to successfully install Eclipse. How to solve incompa…
Suggested Courses
Course of the Month7 days, 23 hours left to enroll

765 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question