Java Jtable展示从数据库中获取的数据

MySQL数据库表信息

#创建数据库
create DATABASE STUDENT;
#使用student数据库
use student;
#建表
create table stu_info(
id int(10) not null PRIMARY key auto_increment,
name VARCHAR(20) not null,
fromSchool varchar(50) not null,
region VARCHAR(50) not null);
#插入数据
insert into stu_info VALUES(1,'ganxiang','第一中学','贵州');

在这里插入图片描述

Java代码

在这里插入图片描述

实体类代码

package ShowDbData;

import java.sql.ParameterMetaData;

/**
 * @program: Training
 * @description: stu_info实体类
 * @create: 2021-01-06 09:35
 **/
public class Stu_info {
    private Integer id;
    private String name;
    private String fromSchool;
    private String region;


    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    @Override
    public String toString() {
        return "Stu_info{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", fromSchool='" + fromSchool + '\'' +
                ", region='" + region + '\'' +
                '}';
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getFromSchool() {
        return fromSchool;
    }

    public void setFromSchool(String fromSchool) {
        this.fromSchool = fromSchool;
    }

    public String getRegion() {
        return region;
    }

    public void setRegion(String region) {
        this.region = region;
    }

}

主要代码

package ShowDbData;

/**
 * @program: Training
 * @description: 直接展示从数据库中获取的数据 ----on esgyn
 * @create: 2021-01-06 15:06
 **/

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;
import java.util.LinkedList;
import java.util.List;


public class ShowData {

    //获取数据库中的数据并以list返回
    private static List<Stu_info> getDbData() throws ClassNotFoundException, SQLException {
        //1,注册驱动信息
        Class.forName("com.mysql.cj.jdbc.Driver");
        //2,获取连接对象
        String url ="jdbc:mysql://localhost:3306/student?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8";
        Connection conn= DriverManager.getConnection(url,"root","123456");
        String sql="select id,name,fromSchool,region from stu_info";
        //3,连接对象conn的方法prepareStatement获取SQL语句的预编译对象
        PreparedStatement parameter =conn.prepareStatement(sql);
        //4,执行sql
        ResultSet result =parameter.executeQuery();
        //返回的数据List
        LinkedList<Stu_info> list =new LinkedList<>();
        while (result.next()){

            Stu_info stu_info =new Stu_info();
            stu_info.setId(result.getInt("id"));
            stu_info.setName(result.getString("name"));
            stu_info.setFromSchool(result.getString("fromSchool"));
            stu_info.setRegion(result.getString("region"));
            list.add(stu_info);
            System.out.println("id:"+result.getObject("id")+" "+"name:"+result.getObject("name")+" "
                    +"fromSchool:"+result.getString("fromSchool")+" "+"region:"+result.getString("region"));
        }
        result.close();
        parameter.close();
        conn.close();

        return list;

    }
    //创建窗口,以列表展示从数据库中获取的数据
    private static void showFrame(List<Stu_info> list){

        //1,设定窗口
        JFrame frame =new JFrame("从mysql中获取数据并展示~");
        frame.setLocation(700,400);
        frame.setSize(500, 300);
        frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);


        //2,添加table
        JTable table =null;
        String [] index={"id","name","fromSchool","region"};
        Object [][] data=new Object[list.size()][index.length];
        //3,向data中添加数据
        for (int i = 0; i < list.size(); i++) {
            Stu_info stu_info =list.get(i);
            data[i][0]=stu_info.getId();
            data[i][1]=stu_info.getName();
            data[i][2]=stu_info.getFromSchool();
            data[i][3]=stu_info.getRegion();

        }
        //4,创建一个默认的表格模型
        DefaultTableModel defaultModel = new DefaultTableModel(data, index);
        table=new JTable(defaultModel);
        table.setBackground(Color.cyan);
        table.setPreferredScrollableViewportSize(new Dimension(100, 80));//JTable的高度和宽度按照设定
        table.setFillsViewportHeight(true);

        //5,给表格设置滚动条
        JScrollPane jScrollPane = new JScrollPane();
        jScrollPane.setViewportView(table);

        Font font = new Font("宋体", Font.BOLD, 13);

        //添加button
        JButton button =new JButton("查询");
        button.setBounds(50,10,50,30);

        //添加label
        JLabel label =new JLabel("点击按钮,查询MySQL数据库中的数据:");
        label.setFont(font);
        label.setBounds(1,10,240,30);

        //通过panel组合button,label
        JPanel panel =new JPanel();
        panel.setBackground(Color.GRAY);
        panel.setSize(200,100);
        panel.add(label);
        panel.add(button);

        //6,添加表格、滚动条到容器中
        frame.add(panel, BorderLayout.NORTH);
        frame.setVisible(true);


        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                frame.add(jScrollPane,BorderLayout.CENTER);
                frame.setVisible(true);

            }
        });

    }

    public static void main(String[] args) throws SQLException, ClassNotFoundException {
//        getDbData();
        showFrame(getDbData());
    }
}

展示结果

在这里插入图片描述

在这里插入图片描述

Logo

本社区面向用户介绍CSDN开发云部门内部产品使用和产品迭代功能,产品功能迭代和产品建议更透明和便捷

更多推荐