简体   繁体   English

如何使用rs2xml jar库填充Jtable

[英]How To Populate Jtable Using rs2xml jar library

Dear friends i would like to know how to display the result set to jtable using rs2xml i know jtablename.setmodel(dbutils.setresultsettotable(rs)); 亲爱的朋友,我想知道如何使用rs2xml将结果集显示到jtable,我知道jtablename.setmodel(dbutils.setresultsettotable(rs)); but i would like to know that how to retriev all records and show them in jtablle my code is 但我想知道如何检索所有记录并在jtablle中显示它们,我的代码是

private void search_by_topic() throws SQLException, ClassNotFoundException {
    try
    {
        SessionFactory sf;
        Configuration cfg=new Configuration();
        System.out.println("search_by_topic me agaya");
        cfg.configure("hiber_config/hibernate.cfg.xml");
        sf=cfg.buildSessionFactory();
        Session ses=sf.openSession();
        ses.beginTransaction();
        Query qr1=ses.createQuery("from Topic where chapter_id=:chapter_id");
        qr1.setParameter("chapter_id", chap_id);
        List<Topic> topic_list=qr1.list();
        top_id=topic_list.get(jComboBox3.getSelectedIndex()).getTopic_id();
        System.out.println("Topic ID is "+top_id);
        Query qr2=ses.createQuery("from Test as t where t.import_level=:import_level and t.import_level_id=:import_level_id");
        qr2.setParameter("import_level", topicimport);
        qr2.setInteger("import_level_id",top_id);
        List<Test> test_list=qr2.list();
        //Field[] fields = null;
        System.out.println("Size of test_list is"+test_list.size());
        //Iterator<Test> itr=test_list.iterator();
        int[] test_id=new int[test_list.size()];

        for(int j=0;j<test_list.size();j++)
        {
            System.out.println("Test_List Import Wale me agaya");
            //fields=t.getClass().getDeclaredFields();    
            test_id[j]=test_list.get(j).getId();
            System.out.println("test_id: is "+test_id[j]);
        }
        System.out.println("Size of test_id array is "+test_id.length);
        for(int j=0;j<test_id.length;j++)
        {
            System.out.println("test_id now is "+j);
            int studentid=98;
            String sqlquery="SELECT ST.ID id,ST.STUDENT_ID student_id,ST.attemptNumber attempt_Number,ST.TEST_ID testId,ST.TEST_ID student_test_id,T.description description,T.test_duration test_duration,T.test_score Test_Score,ST.SCHEDULED_START_TIME_BEGIN scheduled_start_time_begin,ST.SCHEDULED_START_TIME_END scheduled_start_time_end,ST.TEST_START_DATE test_start_date,ST.LAST_ACTIVE_TIME test_last_active_time,ST.TEST_ATTEMPTED test_attempted,ST.ALLOW_VIEW_REPORT allow_view_report FROM student_test as ST,test as T WHERE ST.PAYMENT_STATUS='A' AND ST.TEST_ID = T.id AND ST.STUDENT_ID='"+studentid+"' AND ST.TEST_ATTEMPTED='0' AND T.id='"+test_id[j]+"' ORDER BY ST.ID";
            Class.forName("com.mysql.jdbc.Driver");
            java.sql.Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/school_db","root","");
            Statement pst=con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
            rs=pst.executeQuery(sqlquery);
            System.out.println(rs.getRow());
            System.out.println(rs.toString());
            jTable1.revalidate();
            jTable1.setModel(DbUtils.resultSetToTableModel(rs));
            //jTable1.revalidate();
            /*SessionFactory sf1;
            Configuration cfg1=new Configuration();
            System.out.println("join query me agaya");
            cfg1.configure("hiber_config/hibernate.cfg.xml");
            sf1=cfg.buildSessionFactory();
            Session ses1=sf1.openSession();
            ses1.beginTransaction();
            ses1.doWork(new Work()
            {
                @Override
                public void execute(java.sql.Connection cnctn) throws SQLException 
                {
                    java.sql.PreparedStatement pst=cnctn.prepareStatement(sqlquery);
                    rs=pst.executeQuery();
                    System.out.println(rs.toString());
                }

            });
            ses1.getTransaction().commit();
        }
        ses.getTransaction().commit();
        System.out.println("Test Data Retrieved");
        ses.close();*/
        } 
}
    catch(HibernateException e)
    {
        e.printStackTrace();
    } 
}
}

my code is working here correctly and i am able to retrieve all the resultset but in jtable i am only getting the last loop record not every loop record Please help me 我的代码在这里正常工作,我能够检索所有结果集,但是在jtable中,我仅获取最后一个循环记录,而不是每个循环记录,请帮助我

private void search_by_topic() throws SQLException, ClassNotFoundException {
        try
        {

            SessionFactory sf;
            Configuration cfg=new Configuration();
            System.out.println("search_by_topic me agaya");
            cfg.configure("hiber_config/hibernate.cfg.xml");
            sf=cfg.buildSessionFactory();
            Session ses=sf.openSession();
            ses.beginTransaction();
            Query qr1=ses.createQuery("from Topic where chapter_id=:chapter_id");
            qr1.setParameter("chapter_id", chap_id);
            List<Topic> topic_list=qr1.list();
            top_id=topic_list.get(jComboBox3.getSelectedIndex()).getTopic_id();
            System.out.println("Topic ID is "+top_id);
            Query qr2=ses.createQuery("from Test as t where t.import_level=:import_level and t.import_level_id=:import_level_id");
            qr2.setParameter("import_level", topicimport);
            qr2.setInteger("import_level_id",top_id);
            List<Test> test_list=qr2.list();
            //Field[] fields = null;
            System.out.println("Size of test_list is"+test_list.size());
            //Iterator<Test> itr=test_list.iterator();
            int[] test_id=new int[test_list.size()];

            for(int j=0;j<test_list.size();j++)
            {
                System.out.println("Test_List Import Wale me agaya");
                //fields=t.getClass().getDeclaredFields();    
                test_id[j]=test_list.get(j).getId();
                System.out.println("test_id: is "+test_id[j]);
            }
            System.out.println("Size of test_id array is "+test_id.length);
            for(int j=0;j<test_id.length;j++)
            {
                System.out.println("test_id now is "+j);
                int studentid=98;
                String sqlquery="SELECT ST.ID id,ST.STUDENT_ID student_id,ST.attemptNumber attempt_Number,ST.TEST_ID testId,ST.TEST_ID student_test_id,T.description description,T.test_duration test_duration,T.test_score Test_Score,ST.SCHEDULED_START_TIME_BEGIN scheduled_start_time_begin,ST.SCHEDULED_START_TIME_END scheduled_start_time_end,ST.TEST_START_DATE test_start_date,ST.LAST_ACTIVE_TIME test_last_active_time,ST.TEST_ATTEMPTED test_attempted,ST.ALLOW_VIEW_REPORT allow_view_report FROM student_test as ST,test as T WHERE ST.PAYMENT_STATUS='A' AND ST.TEST_ID = T.id AND ST.STUDENT_ID='"+studentid+"' AND ST.TEST_ATTEMPTED='0' AND T.id='"+test_id[j]+"' ORDER BY ST.ID";
                Class.forName("com.mysql.jdbc.Driver");
                java.sql.Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/school_db","root","");
                Statement pst=con.createStatement();
                rs=pst.executeQuery(sqlquery);
                while(rs.next())
                {
                    //JOptionPane.showMessageDialog(null, "Table me Agaaya");
                    System.out.println("Number of rows:- "+rs.getRow());
                    System.out.println(rs.toString());
                }
            }
            ses.getTransaction().commit();
            System.out.println("Test Data Retrieved");
            ses.close(); 
    }
    catch(HibernateException e)
    {
        e.printStackTrace();
    } 
}
}

this is my code and its working fine in system.out.println it showing all data now can u tell me how to pass this data in jtable and to let you know when i use dbutils its also retrieve column name automatically and i am not giving the column name in jtable manually 这是我的代码,它在system.out.println中正常工作,它显示所有数据,现在您可以告诉我如何在jtable中传递此数据,并让您知道当我使用dbutils时,它还会自动检索列名,而我没有给出手动在jtable中的列名

i know jtablename.setmodel(dbutils.setresultsettotable(rs)); 我知道jtablename.setmodel(dbutils.setresultsettotable(rs));

Well DBUtils creates a single TableModel DBUtils会创建一个TableModel

but in jtable i am only getting the last loop record not every loop record 但是在jtable中我只得到最后一个循环记录,而不是每个循环记录

You keep replacing the old TableModel with a new TableModel. 您一直用新的TableModel替换旧的TableModel。

So you have two choices: 因此,您有两种选择:

  1. You need to create multiple tables, one for each TableModel and add each JTable to the frame 您需要创建多个表,每个TableModel一个,并将每个JTable添加到框架中

  2. You need to copy the data from each TableModel into a master TableModel and then display the master TableModel into in single JTable. 您需要将数据从每个TableModel复制到主TableModel,然后将主TableModel显示到单个JTable中。 So this means that outside of the loop your create a DefaultTableModel with just the column names and 0 rows of data. 因此,这意味着在循环之外,您将创建一个DefaultTableModel,其中仅包含列名和0行数据。 Then instead each loop your then copy each row of data from the DBUtils model to your main TableModel. 然后,每个循环又将每行数据从DBUtils模型复制到主TableModel。 Then outside the loop your create the table using the main TableModel. 然后在循环之外,使用主TableModel创建表。

Edit: 编辑:

The basic structure of the code would be something like: 该代码的基本结构如下所示:

// Create an empty table model

String[] columnNames = {"Column1", "Column2", ...};
DefaultTableModel groupModel = new DefaultTableModel(columnNames,0);

...

// loop for all the ids

for(int j=0;j<test_id.length;j++)
{
      ... 

    // copy the data from the idc table model to the group table model

    DefaultTableModel idModel = DbUtils.resultSetToTableModel(rs);

    for (int i = 0; I < idModel.getRowCount())
    {
        Vector<Object> row = new Vector<Object>();

        for (int j = 0; j < rsModel.getColumnCount()
            row.addElement( rsModel.getValueAt(i, j); 

        groupModel.addRow( row );
    }
}

JTable table = new JTable( groupModel );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM