繁体   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