如何将数据库中的所有数据显示为jtable? [英] how to display all the data from the database to jtable?

查看:798
本文介绍了如何将数据库中的所有数据显示为jtable?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们在数据库中有一个名为data的表,我们希望使用NetBeans IDE检索和显示JTable组件中的所有数据。数据库中的每一行都应该显示在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.

推荐答案

另外,请记住MVC是游戏的名称。扩展AbstractTableModel以创建将向JTable提供数据的模型。

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.

您需要实现以下方法:

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

最后将你的模型设置为JTable:

and finally set your model to the JTable:

    myJTable.setModel(new MyModel());

这样的事情:

public class MyModel extends AbstractTableModel {

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

    public MyModel () {

        try {
            Class.forName("com.mysql.jdbc.Driver");
            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();
                System.out.println(msg);
            }
        } catch (ClassNotFoundException e) {
            String msg = "The com.mysql.jdbc.Driver is missing\n"
                    + "install and rerun the application";
            System.out.println(msg);
            System.exit(1);
        } 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);
                default:
                    return null;
            }
        } catch (SQLException ex) {
            System.out.println(ex.getMessage());
        }
        return null;
    }
}

这篇关于如何将数据库中的所有数据显示为jtable?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆