Most simple code to populate JTable from ResultSet

2018-12-31 15:39发布

I googled the whole day and no luck. I call getnPrintAllData() method after pressing OK button. So the code is:

public class DatabaseSQLiteConnection {
    Connection conn = null;
    PreparedStatement statement = null;
    ResultSet res = null;

    public DatabaseSQLiteConnection(){
        try{
            Class.forName("org.sqlite.JDBC");
            conn = DriverManager.getConnection("jdbc:sqlite:test.sqlite");
            statement = conn.prepareStatement("SELECT * from product_info;");
        }
        catch(Exception e){
            e.printStackTrace();
        }
    }   

    public void getnPrintAllData(){
        String name, supplier, id;
        DefaultTableModel dtm = new DefaultTableModel();
        Window gui = new Window(); //My JPanel class        
        try{
            res = statement.executeQuery();
            testResultSet(res);
            ResultSetMetaData meta = res.getMetaData();
            int numberOfColumns = meta.getColumnCount();
            while (res.next())
            {
                Object [] rowData = new Object[numberOfColumns];
                for (int i = 0; i < rowData.length; ++i)
                {
                    rowData[i] = res.getObject(i+1);
                }
                dtm.addRow(rowData);
            }
            gui.jTable1.setModel(dtm);
            dtm.fireTableDataChanged();
            //////////////////////////

        }
        catch(Exception e){
            System.err.println(e);
            e.printStackTrace();
        }
        finally{
            try{
                res.close();
                statement.close();
                conn.close();
            }
            catch(Exception e){
                e.printStackTrace();
            }
        }
    }    

    public void testResultSet(ResultSet res){
        try{
            while(res.next()){
                System.out.println("Product ID: "+ res.getInt("product_id"));
                System.out.println("Product name: "+ res.getString("product_name"));
                System.out.println("Supplier: "+ res.getString("supplier"));
            }        
        }
        catch(Exception e){
            e.printStackTrace();
        }
    }
}

My testResultSet() method is working properly. Now, how to change my code so that it works, or what is the most simple code to make DefaultTableModel from ResultSet ? Thanks in advance.

Edit: I am reciving java.lang.IllegalStateException: SQLite JDBC: inconsistent internal state error.

10条回答
何处买醉
2楼-- · 2018-12-31 16:19

go here java tips weblog

then,put in your project : listtabelmodel.java and rowtablemodel.java add another class with this code:

    enter code here
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package comp;

import java.awt.*;
import java.sql.*;
import java.util.*;
import javax.swing.*;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
import javax.swing.table.*;

public class TableFromDatabase extends JPanel {

    private Connection conexao = null;

    public TableFromDatabase() {
        Vector columnNames = new Vector();
        Vector data = new Vector();

        try {
            //  Connect to an Access Database
            conexao = DriverManager.getConnection("jdbc:mysql://" + "localhost"
                    + ":3306/yourdatabase", "root", "password");

            //  Read data from a table
            String sql = "select * from tb_something";
            Statement stmt = conexao.createStatement();
            ResultSet rs = stmt.executeQuery(sql);
            ResultSetMetaData md = rs.getMetaData();
            int columns = md.getColumnCount();

            //  Get column names
            for (int i = 1; i <= columns; i++) {
                columnNames.addElement(md.getColumnName(i));
            }

            //  Get row data
            while (rs.next()) {
                Vector row = new Vector(columns);

                for (int i = 1; i <= columns; i++) {
                    row.addElement(rs.getObject(i));
                }

                data.addElement(row);
            }

            rs.close();
            stmt.close();
            conexao.close();
        } catch (Exception e) {
            System.out.println(e);
        }

        //  Create table with database data
        JTable table = new JTable(data, columnNames) {
            public Class getColumnClass(int column) {
                for (int row = 0; row < getRowCount(); row++) {
                    Object o = getValueAt(row, column);

                    if (o != null) {
                        return o.getClass();
                    }
                }

                return Object.class;
            }
        };

        JScrollPane scrollPane = new JScrollPane(table);
        add(scrollPane);

        JPanel buttonPanel = new JPanel();
        add(buttonPanel, BorderLayout.SOUTH);
    }

    public static void main(String[] args) {

        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                JFrame frame = new JFrame("any");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

                //Create and set up the content pane.
                TableFromDatabase newContentPane = new TableFromDatabase();
                newContentPane.setOpaque(true); //content panes must be opaque
                frame.setContentPane(newContentPane);

                //Display the window.
                frame.pack();
                frame.setVisible(true);
            }
        });

    }
}

then drag this class to you jframe,and it's done

it's deprecated,but it works.........

查看更多
零度萤火
3楼-- · 2018-12-31 16:27

With all factors put into consideration, with regard to code architecture using modular programming would work very well and with more simplicity in the code. Write a simple

getData() function @returns a 2D array of the data from the database.

pass this funtion to the constructor of the JTabel() constructor i.e

JTabel myTable = new JTable(getData(),columnsArray);

In this case the second argument: columnsArray is a single dimensional array that has the column names

String[] columns = {{"ID","DataOfBirth","Age","Grade","Marks","RegNumber"}};

pass the JTable object to a JScrollPane then you are done, right after adding the ScrollPane to the container ofcourse

JScrollPane scrollPane = new JScrollPane(myTable);

JFrame myFrame = new JFrame();
myFrame.add(scrollPane);

Here is a sample function getData() that queries the database for the data that later is passed on to the JTable

public String[][] getRecords() {
    try (Connection conect = DriverManager.getConnection("jdbc:mysql://localhost:3306/online_students_registration", "root", "")) {
        Statement stm = conect.createStatement();
        String SELECT_QUERY = "SELECT COUNT(*) FROM medicalrecords ;";
        ResultSet cursor = stm.executeQuery(SELECT_QUERY);
        while (cursor.next()) {
            rows = cursor.getInt("COUNT(*)");
            System.out.println("Table will have " + rows + " Rows");
        }
        System.err.println("Contacts row count is obtained!!");
        if (rows < 1) {
            JOptionPane.showMessageDialog(null, "There is NO DATA");
            //contactsRowsCount = 1;
            //System.out.println("Table rows succefully reset to  " + contactsRowsCount + " Rows");
            dataValues = new String[1][8];
            //dataValues[1][5] = "No Values";

            for (int i = 0; i < 1; i++) {
                for (int j = 0; j < 8; j++) {
                    if (j == 0) {
                        dataValues[i][j] = "No Details Available";
                        System.out.println("" + dataValues);
                    } else {
                        dataValues[i][j] = "...";
                        System.out.println("Contacts" + dataValues[i][j]);
                    }
                }
            }

            System.out.println("Return statement is being executed on 0 rows ");
            //return doctoredDataValues;
        } else if (rows > 0) {

            System.out.println("obtain contacts code is being run under  " + rows + " Rows");
            dataValues = new String[rows][8];    //declare array for contacts table data
            System.out.println("[ Line 1584 ]The dataValues object for the JTable succefully set");

            String SELECT_QUERY_CONTACT = "SELECT * FROM medicalrecords; ";

            //OBTAIN CONTACTS FROM DB WITH REGARD TO CONTACT CATEGORY SPECIFIED
            ResultSet contactsTableCursor = stm.executeQuery(SELECT_QUERY_CONTACT);
            //use iterator-algorithm to insert values into the JTable
            for (int i = 0; contactsTableCursor.next() && i < rows; i++) {
                for (int j = 0; j < 8; j++) {
                    dataValues[i][j] = contactsTableCursor.getString(j + 1);
                    System.out.println("Contacts" + dataValues[i][j]);
                }
            }
        }
        JOptionPane.showMessageDialog(null, "Medical Details Added Succefully!!");
    } catch (SQLException e) {

        JOptionPane.showMessageDialog(null, "Unable to Obtain contacts:Server is Offline(LINE 1568)" + e.getMessage());
    }

    return dataValues;

}
查看更多
人间绝色
4楼-- · 2018-12-31 16:29

The JTable constructor accepts two arguments 2dimension Object Array for the data, and String Array for the column names.

eg:

import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;

public class Test6 extends JFrame {

    public Test6(){     
        this.setSize(300,300);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Mpanel m = new Mpanel();
        this.add(m,BorderLayout.CENTER);        
    }


    class Mpanel extends JPanel {       

        JTable mTable;
        private Object[][] cells = {{"Vivek",10.00},{"Vishal",20.00}};
        private String[] columnNames = { "Planet", "Radius" };
        JScrollPane mScroll;

        public Mpanel(){
            this.setSize(150,150);
            this.setComponent();
        }

        public void setComponent(){
            mTable = new JTable(cells,columnNames);
            mTable.setAutoCreateRowSorter(true);
            mScroll = new JScrollPane(mTable);

            this.add(mScroll);
        }
    }

    public static void main(String[] args){     
        new Test6().setVisible(true);
    }
}
查看更多
冷夜・残月
5楼-- · 2018-12-31 16:31

I think this is the Easiest way to populate a table with ResultSet with a method like

FillTable(MyTable, "select * Customers;");

And a very simple method can be made as

public void FillTable(JTable table, String Query)
{
    try
    {
        CreateConnection();
        Statement stat = conn.createStatement();
        ResultSet rs = stat.executeQuery(Query);

        //To remove previously added rows
        while(table.getRowCount() > 0) 
        {
            ((DefaultTableModel) table.getModel()).removeRow(0);
        }
        int columns = rs.getMetaData().getColumnCount();
        while(rs.next())
        {  
            Object[] row = new Object[columns];
            for (int i = 1; i <= columns; i++)
            {  
                row[i - 1] = rs.getObject(i);
            }
            ((DefaultTableModel) table.getModel()).insertRow(rs.getRow()-1,row);
        }

        rs.close();
        stat.close();
        conn.close();
    }
    catch(InstantiationException | IllegalAccessException | SQLException e)
    {
    }
}
查看更多
登录 后发表回答