user1016195 user1016195 - 1 year ago 170
Java Question

how to display all the data from the database to jtable?

we had a table called data in database and we want to retrieve and display all the data in a JTable component using NetBeans IDE. Every rows in the database should be display in the jtable.

Answer Source

Also, keep in mind that MVC is the name of the game. Extend an AbstractTableModel in order to create a model that will provide data to your JTable.

You will need to implement the following methods:

public int getRowCount()
public int getColumnCount() and 
public Object getValueAt(int rowIndex, int columnIndex)

and finally set your model to the JTable:

    myJTable.setModel(new MyModel());

Something like this:

public class MyModel extends AbstractTableModel {

    private Connection con;
    private Statement stmt;
    private ResultSet rs;

    public MyModel () {

        try {
            try {
                con = DriverManager.getConnection("jdbc:mysql://localhost:3306/databasename?useUnicode=true&characterEncoding=UTF-8",
                        "root", "password");
                stmt = con.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
                rs = stmt.executeQuery("select * from tablename");

            } catch (SQLException e) {
                String msg = "MyModel(): Error Connecting to Database:\n"
                        + e.getMessage();
        } catch (ClassNotFoundException e) {
            String msg = "The com.mysql.jdbc.Driver is missing\n"
                    + "install and rerun the application";
        } finally {


    public int getRowCount() {
// count your rows and return 
        return count;

    public int getColumnCount() {
// how many cols will you need goes here
        return 3;

    public Object getValueAt(int rowIndex, int columnIndex) {
        try {
            rs.absolute(rowIndex + 1);
            switch (columnIndex) {
                case 0: 
                    return rs.getInt(1);
                case 1:
                    return rs.getString(2);
                case 2:
                    return rs.getString(6);
                    return null;
        } catch (SQLException ex) {
        return null;