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 环境的新手,所以如果有人可以帮助我解决这个问题,我将不胜感激,并提前感谢您 :)

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

2 回答 2

2

您不断添加到同一个向量行。尝试为 rs.next() 的每次迭代创建一个新实例。

于 2012-04-13T13:55:39.733 回答
1

您的 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 );     
于 2012-04-13T14:45:51.247 回答