0
I used this coding to retrieve the Mysql data to the JTable.but it returns only the first data row of the relevant table of the database but then again it count the number of rows correctly and all it returns is same copy of the first row equal to the row count.

I'm new to Java and netbeans environment so if someone can help me to solve this problem i'll be really grateful and thank you in advance :)

    Class.forName("com.mysql.jdbc.Driver").newInstance();
    Connection con = DriverManager.getConnection("jdbc:mysql://localhost/data",          "root", "1122");    
    Statement stat = (Statement) con.createStatement();
    stat.executeQuery("select * from reserve;");
    ResultSet rs=stat.getResultSet();
    ResultSetMetaData md = rs.getMetaData();
    int columnCount = md.getColumnCount();
    Vector data=new Vector();
    Vector columnNames= new Vector();
    Vector row = new Vector(columnCount);

    for(int i=1;i<=columnCount;i++){
        columnNames.addElement(md.getColumnName(i));
    }
    while(rs.next()){
    for(int i=1; i<=columnCount; i++){
    row.addElement(rs.getObject(i));
    }      
    data.addElement(row);
    }        
    DefaultTableModel model = new DefaultTableModel(data, columnNames);
    jTable1.setModel( model );     
senrulz
  • 121
  • 1
  • 2
  • 12

2 Answers2

2

You keep adding to the same Vector row. Try creating a new instance for each iteration of rs.next().

1

You have an error with your Vector. Consider using something like :

    Vector data = new Vector(columnCount);
    Vector row = new Vector(columnCount);
    Vector columnNames = new Vector(columnCount);


    for (int i = 1; i <= columnCount; i++) {
        columnNames.addElement(md.getColumnName(i));
    }
    while (rs.next()) {
        for (int i = 1; i <= columnCount; i++) {
            row.addElement(rs.getObject(i));

        }
        data.addElement(row);
        row = new Vector(columnCount); // Create a new row Vector
    }
    DefaultTableModel model = new DefaultTableModel(data, columnNames);
    jTable1.setModel( model );     
alain.janinm
  • 19,951
  • 10
  • 65
  • 112