如何在java中保持ResultSet打开?

时间:2013-12-18 12:55:31

标签: java swing resultset

我正在为创建JTable的java文件传递值。

ResultSet res = np.InvestmentByInvestType(IType);
 String tablename = "Investment By Invest Type";
 int customAmt = np.showCustomizeInvestAmount1(IType);
 CommonTable ct = new CommonTable();
 ct.CommonSearchTable(res, customAmt,tablename);

ResultSet res = np.InvestmentByInvestType(IType); String tablename = "Investment By Invest Type"; int customAmt = np.showCustomizeInvestAmount1(IType); CommonTable ct = new CommonTable(); ct.CommonSearchTable(res, customAmt,tablename);

我在CommonSearchTable中创建了一个按钮,使用ResultSet导出JTable数据。但它显示错误“ResultSet关闭后不允许操作”。 CommonSearchTable.java中的方法如下:

public void CommonSearchTable( final ResultSet res, int totally, final String tablename) throws SQLException 
{

        JButton exportTable= new JButton ("Export");

        ResultSetMetaData metaData = res.getMetaData();
        // names of columns
        Vector<String> columnNames = new Vector<String>();
        int columnCount = metaData.getColumnCount();

        for (int column = 1; column <= columnCount; column++) 
        {
            columnNames.add(metaData.getColumnName(column));
        }
        // data of the table
        Vector<Vector<String>> data = new Vector<Vector<String>>();
        while (res.next()) 
        {
            Vector<String> vector = new Vector<String>();
            for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) 
            {
                vector.add(res.getString(columnIndex));                     
            }
            data.add(vector);
        }

        model1 = new DefaultTableModel(data, columnNames);
        JTable table = new JTable(model1);
        int rows = table.getRowCount();
        Sorter = new TableRowSorter<DefaultTableModel> (model1);
        table.setRowSorter(Sorter);
        showSearchPages(30, 1);
        table.setModel(model1);
        String showTotal = "Total Amount : Rs."+totally+"/-"; 
        JPanel footer = new JPanel();
        JLabel show = new JLabel(showTotal);
        box1.setBounds(10,30,800,30);           
        show.setBounds(10, 60, 100, 30);
        show.setFont(new Font("Tahoma",Font.BOLD,16));            
        footer.add(box1);
        footer.add(show);
        footer.setPreferredSize(new Dimension(800,100));   
        JPanel holdingPanel = new JPanel(null);  
        JScrollPane sp = new JScrollPane(table); 
        JButton print = new JButton ("Print");
        print.setBounds(10,10,100,30);
        exportTable.setBounds(120,10,100,30);
        sp.setBounds(10,50,780,580);
        holdingPanel.add(print);
        holdingPanel.add(exportTable);
        holdingPanel.add(sp);  
        JFrame f = new JFrame("Search Results");  
        f.getContentPane().add(holdingPanel,BorderLayout.CENTER);  
        f.getContentPane().add(sp.getVerticalScrollBar(),BorderLayout.EAST);  
        f.getContentPane().add(footer,BorderLayout.SOUTH);
        f.setPreferredSize(new Dimension(850,680));
        f.pack();  
        f.setLocationRelativeTo(null);  
        f.dispose();  
        f.setResizable(false);
        f.setIconImage(img.getImage());
        f.setVisible(true);

        exportTable.addActionListener(new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent aev)
            {
                try 
                {                         
                     ExportFile ef = new ExportFile();
                     ef.WriteFile(res, tablename);                        
                } 
                catch (SQLException | IOException ex) 
                {
                    Logger.getLogger(CommonTable.class.getName()).log(Level.SEVERE, null, ex);
                }
            }                                
        });

        print.addActionListener(new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent e)
            {
               PrinterJob printJob = PrinterJob.getPrinterJob();
               if (printJob.printDialog())
                    try 
                    { 
                      printJob.print();
                    } 
                    catch(PrinterException pe) 
                    {
                    }
            }
        });
}

请告诉我。

2 个答案:

答案 0 :(得分:6)

正如您可以在docs中了解结果集:

  

当Statement对象时,ResultSet对象自动关闭   生成它的是关闭,重新执行或用于检索下一个   由多个结果序列产生。

这意味着您必须在关闭数据库连接之前将结果数据复制到另一个数据结构(如列表,地图,适合您的需要)。

答案 1 :(得分:0)

Look at this example this will help you. In this example we fetch all data from database on jcombobox actionlistener. Change this according to your need.

        class Credit extends JFrame implements ActionListener{
        private String value4="0";
        private String val="0";
        private String val1="0";
        private String jama="0",baki="0";
        private String nettdate="0",nettb="0",nettbal="0";
        private int row=0,count=0,aa=0,bb=0,t1=0;
        private String tj1="0",tb1="0",gt1="0";


        String h[]={"TID","Date","Jama","Baki","Nett"};
        private TableModel buildTableModel(ResultSet rs) throws SQLException {
            ResultSetMetaData metaData = rs.getMetaData();
        // names of columns

            Vector<String> columnNames = new Vector<String>();

            int columnCount = metaData.getColumnCount();


            for (int column = 0; column < columnCount; column++) {

                //columnNames.add(metaData.getColumnName(column));
                columnNames.add(h[column]);

            }

            // data of the table
                //Vector<Object> vector = new Vector<Object>();
                //Vector<Object> vector1 = new Vector<Object>();
                Vector<String> vector1 = new Vector<String>();
                Vector<String> vector2 = new Vector<String>();

            Vector<Vector<String>> data = new Vector<Vector<String>>();
            //Vector<Vector<Object>> data = new Vector<Vector<Object>>();
            while (rs.next()) {


                //for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
                    Vector<String> vector = new Vector<String>();

                    //vector.add(rs.getString(columnIndex));
                    vector.add(rs.getString(1));
                    vector.add(rs.getString(2));
                    vector.add(rs.getString(3));
                    vector.add(rs.getString(4));
                    vector.add(rs.getString(5));
                  //  System.out.println(vector);
                //}
                    count++;
                data.add(vector);
                //System.out.println(data.get(0).get(0));
            }

            for(int i=0;i<count;i++){
                //aa=aa+Integer.parseInt(data.get(i).get(2));
                aa=aa+Integer.parseInt(table.getValueAt(i, 2).toString());
                System.out.println(table.getValueAt(i, 2).toString());
                System.out.println("A:"+aa);
                //bb=bb+Integer.parseInt(data.get(i).get(3));
                bb=bb+Integer.parseInt(table.getValueAt(i, 3).toString());
                System.out.println(table.getValueAt(i, 3).toString());
                System.out.println("B:"+bb);

            }
            tj1=Integer.toString(aa);
            System.out.println("TJ:"+tj1);
                //header1 = new Vector<String>();
            vector1.add("");
            vector1.add("Total");
            vector1.add(tj1);

            tb1=Integer.toString(bb);
            //header1 = new Vector<String>();
            //header3.add("Total");
            vector1.add(tb1);
            vector1.add("");
            //data1.setSize(table1.getRowCount()+1);
            //data1.set(table1.getRowCount()-1, header3);
            //data.setSize(count++);
            //data.setSize(table.getRowCount()+1);
            //data.set(count, header2);
            System.out.println("h2:"+vector1);

            data.add(vector1);
            System.out.println("data:"+data);

            //data.set(table.getRowCount()-1, header2);


            t1=Integer.parseInt(tb1)-Integer.parseInt(tj1);
            gt1=Integer.toString(t1);
            System.out.println("GT:"+gt1);

            vector2.add("");
            vector2.add("Nett Balance");
            //header4.add("");
            vector2.add("");
            vector2.add(gt1);
            vector2.add("");
            //data.setSize(table.getRowCount()+1);
            //data.setSize(count++);
            data.add(vector2);
            System.out.println("data1:"+data);
            //data.set(count, header3);
            //data.set(table.getRowCount()-1, header3);
            //header2.add("");
            count=0;
            aa=0;
            bb=0;
            t1=0;
            tj1="0";
            tb1="0";
            gt1="0";

            return new DefaultTableModel(data, columnNames);
        }
        private static final int GAP = 5;
        private static final Font BTN_FONT = new Font(Font.DIALOG, Font.PLAIN, 15);
        private JPanel mainPanel = new JPanel();
        JButton add,cancel,show,search,print,update,delete,net;
        JTextField jTextField,jTextField1,jTextField2,jTextField3,jTextField4,jTextField5;
        JComboBox jComboBox;
        String Select[]={"Select"};
        Object name,s1;
        String an="0",nam="0",mono="0",cit="0";
        int token=0,tid=1,a,stid=0;
        JFrame f;
        AbstractAction action;
        private String id;
        Connection con=null;
                Statement st=null;
                ResultSet rs=null;
        //private String stid;
                            JPanel tablePanel;
                            DefaultTableModel model;
                            DefaultTableModel model1;
                            JTable table,table3;
      private Vector<Vector<String>> data; //used for data from database
      private Vector<Vector<String>> data1; //used for data from database
        private Vector<String> header; //used to store data header
        private Vector<String> header2; //used to store data header
        private Vector<String> header3;
        private Vector<String> header4;
        private JLabel jlab4,jlab5,jlab6,jlab7;

        Credit(JFrame frm){
            Toolkit tk=Toolkit.getDefaultToolkit();
        Image img=tk.getImage("1.jpg");
        setIconImage(img);
            JPanel creditPanel = createPanel1("Customer Credit & Debit Amount");
            tablePanel = createPanel2("Customer Credit & Debit Table");
            creditPanel.setBackground(Color.WHITE);
            tablePanel.setBackground(Color.WHITE);
            mainPanel.setLayout(new BorderLayout());
            mainPanel.setBorder(BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP));
            mainPanel.add(creditPanel, BorderLayout.PAGE_START);
            mainPanel.add(tablePanel, BorderLayout.CENTER);
            creditPanel.setVisible(true);
            mainPanel.setBackground(Color.BLACK);
            frm.add(mainPanel);

        } 
        private JPanel createPanel2(String title){
            tablePanel=new JPanel();
            tablePanel.setLayout(new BoxLayout(tablePanel,BoxLayout.Y_AXIS));

            header = new Vector<String>();
            header.add("TID"); 
            header.add("Date"); 
            header.add("Jama"); 
            header.add("Baki"); 
            header.add("Nett"); 
            header4 = new Vector<String>();
            header4.add("A/C No."); 
            header4.add("Name"); 
            //header4.add("Date"); 
            header4.add("Mobile"); 
            header4.add("City"); 
            model=new DefaultTableModel(data,header);
            model1=new DefaultTableModel(data1,header4);
            table = new JTable(model);
            table3 = new JTable(model1);
            table.setRowSorter(new TableRowSorter(model));
            table.setRowHeight(30);
            table3.setRowHeight(30);
            table.setFont(new Font("Times New Roman",Font.BOLD,15));
            table3.setFont(new Font("Times New Roman",Font.BOLD,15));
            table.getTableHeader().setFont( new Font( "Times New Roman" , Font.BOLD, 15 ));
            table3.getTableHeader().setFont( new Font( "Times New Roman" , Font.BOLD, 15 ));
            table.setDefaultRenderer(Object.class, new TableCellRenderer(){
            table3.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
            table3.getColumnModel().getColumn(0).setPreferredWidth(123);
            table3.getColumnModel().getColumn(1).setPreferredWidth(250);
            table3.getColumnModel().getColumn(2).setPreferredWidth(123);
            table3.getColumnModel().getColumn(3).setPreferredWidth(125);
            JScrollPane scroll=new JScrollPane(table);
            JScrollPane scroll1=new JScrollPane(table3);
            scroll1.setPreferredSize(new Dimension(50,63));

JPanel p=new JPanel();
JButton btn=new JButton("Print");
JButton btn1=new JButton("Export");
p.add(btn);
p.add(btn1);
tablePanel.add(p);
            tablePanel.add(scroll1);
            tablePanel.add(scroll);

            tablePanel.setBorder(BorderFactory.createTitledBorder(title));
            return tablePanel;
        }
        private JPanel createPanel1(String title) {
            JPanel addUnitPanel = new JPanel();
            addUnitPanel.setLayout(new GridLayout(4,1, GAP, GAP));


            JLabel jlab=new JLabel("Name:");
            jComboBox=new JComboBox(Select);//Select
            jlab.setPreferredSize(new Dimension(100,10));
            jComboBox.setPreferredSize(new Dimension(150,30));

            jComboBox.addActionListener(new ActionListener(){
                private int b=0,a=0;
                private String tj="0";
                private String tb="0";
                private int t=0;
                private String gt="0";


            public void actionPerformed(ActionEvent ae){
                try
            {
                Connection con=null;
                Statement st=null;
                ResultSet rs=null;
                           // ResultSet rs1=null;

                Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                String url=null,userID=null,password=null;
                        String dbFileName=null;
                        String sql=null;

                        dbFileName = "C:/Program Files/Shop/shop.accdb";
                                    //userID = "Admin";
                                    password = "3064101991";
                        url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};"+
                                "DBQ="+dbFileName+";"+
                                "Pwd="+password+";";
                        //sql = "SELECT * FROM tblUserProfile";
                        Object name=jComboBox.getSelectedItem();
                        con=DriverManager.getConnection(url);//,"system","manager"
                            st=con.createStatement();
                model.setRowCount(0);
                                    model1.setRowCount(0);
                                    b=0;
                                    a=0;
                                    tj="0";
                                    tb="0";
                                    t=0;
                                    gt="0";
                                    an="0";nam="0";mono="0";cit="0";

                                    DBEngine dbengine = new DBEngine();
            data = dbengine.getJamaCustomer(name);
            data1 = dbengine.getIdName(name);
            System.out.println("data:"+data1);


            Object[] d3={data1.get(0).get(0),data1.get(0).
        get(1),data1.get(0).get(3),data1.get(0).get(4)};
            model1.addRow(d3);
            JTable table1=new JTable(data,header);
            for(int i=0;i<table1.getRowCount();i++){
            Object[] d={data.get(i).get(0),data.get(i).get(1),
        data.get(i).get(2),data.get(i).get(3),data.get(i).get(4)};
            model.addRow(d);

            }
            for(int i=0;i<table1.getRowCount();i++){
                a=a+Integer.parseInt(data.get(i).get(2));

                b=b+Integer.parseInt(data.get(i).get(3));
            }
            tj=Integer.toString(a);
            tb=Integer.toString(b);
            Object[] d1={"","Total",tj,tb,""};
            model.addRow(d1);



            t=Integer.parseInt(tb)-Integer.parseInt(tj);
            gt=Integer.toString(t);
            Object[] d2={"","Nett Balance","",gt,""};
            model.addRow(d2);

            table = new JTable(model);
            table3 = new JTable(model1);


            table.setRowHeight(30);
            table3.setRowHeight(30);
            JScrollPane scroll=new JScrollPane(table);
            JScrollPane scroll1=new JScrollPane(table3);
            //scroll.setBackground(Color.red);
            tablePanel.add(scroll1);
            tablePanel.add(scroll);
                    rs.close();
                           // rs1.close();
                            st.close();
                            con.close();
            }
            catch(Exception e)
            {
                System.out.println("GG"+e);
            }

            }
            });

            JPanel p1=new JPanel();
            p1.add(jlab); 
            p1.add(jComboBox);
            addUnitPanel.add(p1);

            loadcombo2();

            addUnitPanel.setBorder(BorderFactory.createTitledBorder(title));
            return addUnitPanel;
        } 

        void loadcombo2()
        {
            try
            {
                Connection con=null;
                Statement st=null;
                ResultSet rs=null;
                           // ResultSet rs1=null;

                Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                String url=null,userID=null,password=null;
                        String dbFileName=null;
                        String sql=null;

                        dbFileName = "C:/Program Files/Shop/shop.accdb";
                                    //userID = "Admin";
                                    password = "3064101991";
                        url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};"+
                                "DBQ="+dbFileName+";"+
                                "Pwd="+password+";";
                        //sql = "SELECT * FROM tblUserProfile";
                        con=DriverManager.getConnection(url);//,"system","manager"
                                    st=con.createStatement();

                rs= st.executeQuery("select distinct(Name) from ManageCustomer");
                //rs1=st.executeQuery("select Unit from AddUnit");
                            while(rs.next())
                {
                    jComboBox.addItem(rs.getString(1));
                                    //jComboBox1.addItem(rs1.getString(1));
                }
                rs.close();
                           // rs1.close();
                            st.close();
                            con.close();
            }
            catch(Exception e)
            {
                System.out.println("GG"+e);
            }

        }


    @Override
    public void actionPerformed(ActionEvent ae){
        if(ae.getSource()==print){
    //Your print code
    }
    if(ae.getSource()==Export){
    //Add jComboBox.addActionListener code here
    }
    }

        public static void main(String args[]){
            JFrame frm=new JFrame("Title");
            Credit b=new Credit(frm);
            //frm.setSize(650, 236);
            frm.setSize(650, 700);
            frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frm.setResizable(false);
            frm.setLocationRelativeTo(null);
            frm.show();
        }

    }