2012-04-13 119 views
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. 

我是新來的Java和NetBeans環境,因此,如果有人能幫助我解決這個問題,我會非常感激和感謝你提前:)檢索MySQL數據到JTable在Netbeans的

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);  

回答

1

您的向量出現錯誤。考慮使用類似的東西:

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);  
+0

非常感謝你的快速反應:),它的工作!再次感謝你! – senrulz 2012-04-13 15:09:41

2

您繼續添加到相同的矢量行。嘗試爲rs.next()的每次迭代創建一個新實例。

+0

是啊現在我明白了,就像上面的答案解釋!並非常感謝你的幫助:) – senrulz 2012-04-13 15:11:07