簡體   English   中英

在Netbeans中將Mysql數據檢索到JTable

[英]Retrieving Mysql data to the JTable in Netbeans

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環境的新手,所以如果有人可以幫助我解決此問題,我將不勝感激,並在此先感謝您:)

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

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

您的Vector錯誤。 考慮使用類似:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM