如何将数据从数据库显示到Java Swing控件的JTable

如何将数据从数据库显示到Java Swing控件的JTable,java,jtable,desktop-application,jform,Java,Jtable,Desktop Application,Jform,关于如何使用Java Swing控件的JTable显示数据库中的数据,我遇到了这个问题。我只是在JForm中从调色板拖放表格 我不知道如何编码。您需要使用JDBC将java程序连接到数据库。 之后,您需要使用ResultSet类提取数据。 您需要了解JDBC的基础知识,并了解数据库的命令。您还需要知道如何通过java处理数据库。因此,请阅读oracle的java在线教程(官方教程),它不会超过一个小时。 生活会更轻松您需要使用JDBC将java程序连接到数据库。 之后,您需要使用ResultSe

关于如何使用Java Swing控件的JTable显示数据库中的数据,我遇到了这个问题。我只是在JForm中从调色板拖放表格


我不知道如何编码。

您需要使用JDBC将java程序连接到数据库。 之后,您需要使用ResultSet类提取数据。 您需要了解JDBC的基础知识,并了解数据库的命令。您还需要知道如何通过java处理数据库。因此,请阅读oracle的java在线教程(官方教程),它不会超过一个小时。
生活会更轻松

您需要使用JDBC将java程序连接到数据库。 之后,您需要使用ResultSet类提取数据。 您需要了解JDBC的基础知识,并了解数据库的命令。您还需要知道如何通过java处理数据库。因此,请阅读oracle的java在线教程(官方教程),它不会超过一个小时。
生活会更轻松

使用以下代码:

import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import java.util.Vector;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;

public class DisplayEmpData extends JFrame implements ActionListener {

    JFrame frame1;
    JLabel l0, l1, l2;
    JComboBox c1;
    JButton b1;
    Connection con;
    ResultSet rs, rs1;
    Statement st, st1;
    PreparedStatement pst;
    String ids;
    static JTable table;
    String[] columnNames = {"User name", "Email", "Password", "Country"};
    String from;

    DisplayEmpData() {

        l0 = new JLabel("Fatching Employee Information");
        l0.setForeground(Color.red);
        l0.setFont(new Font("Serif", Font.BOLD, 20));
        l1 = new JLabel("Select name");
        b1 = new JButton("submit");

        l0.setBounds(100, 50, 350, 40);
        l1.setBounds(75, 110, 75, 20);
        b1.setBounds(150, 150, 150, 20);
        b1.addActionListener(this);

        setTitle("Fetching Student Info From DataBase");
        setLayout(null);
        setVisible(true);
        setSize(500, 500);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        add(l0);
        add(l1);;
        add(b1);
        try {
            Class.forName("com.mysql.jdbc.Driver");  // (1)
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/db_name", "username", "password");  // (2)
            st = con.createStatement();
            rs = st.executeQuery("select uname from emp");
            Vector v = new Vector();
            while (rs.next()) {
                ids = rs.getString(1);
                v.add(ids);
            }
            c1 = new JComboBox(v);
            c1.setBounds(150, 110, 150, 20);

            add(c1);
            st.close();
            rs.close();
        } catch (Exception e) {
        }
    }

    public void actionPerformed(ActionEvent ae) {
        if (ae.getSource() == b1) {
            showTableData();
        }

    }

    public void showTableData() {

        frame1 = new JFrame("Database Search Result");
        frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame1.setLayout(new BorderLayout());
//TableModel tm = new TableModel();
        DefaultTableModel model = new DefaultTableModel();
        model.setColumnIdentifiers(columnNames);
//DefaultTableModel model = new DefaultTableModel(tm.getData1(), tm.getColumnNames());
//table = new JTable(model);
        table = new JTable();
        table.setModel(model);
        table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
        table.setFillsViewportHeight(true);
        JScrollPane scroll = new JScrollPane(table);
        scroll.setHorizontalScrollBarPolicy(
                JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        scroll.setVerticalScrollBarPolicy(
                JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
        from = (String) c1.getSelectedItem();
//String textvalue = textbox.getText();
        String uname = "";
        String email = "";
        String pass = "";
        String cou = "";

        try {
            pst = con.prepareStatement("select * from emp where UNAME='" + from + "'");
            ResultSet rs = pst.executeQuery();
            int i = 0;
            if (rs.next()) {
                uname = rs.getString("uname");
                email = rs.getString("umail");
                pass = rs.getString("upass");
                cou = rs.getString("ucountry");
                model.addRow(new Object[]{uname, email, pass, cou});
                i++;
            }
            if (i < 1) {
                JOptionPane.showMessageDialog(null, "No Record Found", "Error", JOptionPane.ERROR_MESSAGE);
            }
            if (i == 1) {
                System.out.println(i + " Record Found");
            } else {
                System.out.println(i + " Records Found");
            }
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
        }
        frame1.add(scroll);
        frame1.setVisible(true);
        frame1.setSize(400, 300);
    }

    public static void main(String args[]) {
        new DisplayEmpData();
    }
}
import java.awt.*;
导入java.awt.event.*;
导入java.sql.*;
导入java.util.Vector;
导入javax.swing.*;
导入javax.swing.table.DefaultTableModel;
公共类DisplayEmpData扩展JFrame实现ActionListener{
jframe1;
JLabel l0,l1,l2;
JComboBox c1;
按钮b1;
连接con;
结果集rs,rs1;
报表st、st1;
编制报表pst;
字符串ID;
静态JTable表;
String[]columnNames={“用户名”、“电子邮件”、“密码”、“国家”};
串从;
DisplayEmpData(){
l0=新的JLabel(“填写员工信息”);
l0.设置前景(颜色为红色);
l0.setFont(新字体(“衬线”,Font.BOLD,20));
l1=新的JLabel(“选择名称”);
b1=新按钮(“提交”);
l0.立根(100,50,350,40);
l1.立根(75、110、75、20);
b1.立根(150、150、150、20);
b1.添加ActionListener(本);
setTitle(“从数据库获取学生信息”);
setLayout(空);
setVisible(真);
设置大小(500500);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
添加(l0);
加上(l1);;
添加(b1);
试一试{
Class.forName(“com.mysql.jdbc.Driver”);/(1)
con=DriverManager.getConnection(“jdbc:mysql://localhost:3306/db_name“,”用户名“,”密码“;/(2)
st=con.createStatement();
rs=st.executeQuery(“从emp中选择uname”);
向量v=新向量();
while(rs.next()){
ids=rs.getString(1);
v、 添加(ID);
}
c1=新的JComboBox(v);
c1.立根(150、110、150、20);
添加(c1);
圣克洛斯();
rs.close();
}捕获(例外e){
}
}
已执行的公共无效行动(行动事件ae){
如果(ae.getSource()==b1){
showTableData();
}
}
public void showTableData(){
frame1=新的JFrame(“数据库搜索结果”);
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.setLayout(新的BorderLayout());
//TableModel tm=新的TableModel();
DefaultTableModel=新的DefaultTableModel();
model.setColumnIdentifiers(columnNames);
//DefaultTableModel=newDefaultTableModel(tm.getData1(),tm.getColumnNames());
//表=新JTable(型号);
table=新的JTable();
表2.setModel(model);
table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
表.setFillsViewPerthweight(真);
JScrollPane scroll=新的JScrollPane(表);
scroll.setHorizontalScrollBarPolicy(
JScrollPane.水平滚动条(根据需要);
scroll.setVerticalScrollBarPolicy(
JScrollPane.垂直滚动条(根据需要);
from=(字符串)c1.getSelectedItem();
//字符串textvalue=textbox.getText();
字符串uname=“”;
字符串email=“”;
字符串pass=“”;
字符串cou=“”;
试一试{
pst=con.prepareStatement(“从emp中选择*,其中UNAME=”“+from+””);
ResultSet rs=pst.executeQuery();
int i=0;
如果(rs.next()){
uname=rs.getString(“uname”);
email=rs.getString(“umail”);
通过=rs.getString(“upass”);
cou=rs.getString(“ucountry”);
addRow(新对象[]{uname,email,pass,cou});
i++;
}
if(i<1){
showMessageDialog(null,“未找到记录”,“错误”,JOptionPane.Error\u消息);
}
如果(i==1){
System.out.println(i+“找到记录”);
}否则{
System.out.println(i+“找到记录”);
}
}捕获(例外情况除外){
showMessageDialog(null,例如getMessage(),“Error”,JOptionPane.Error_MESSAGE);
}
frame1.添加(滚动);
frame1.setVisible(true);
框架1.设置尺寸(400300);
}
公共静态void main(字符串参数[]){
新的DisplayEmpData();
}
}

编辑:上面的代码以mysql为例。如果不使用mysql,请更改标有(1)和(2)的行。

使用以下代码:

import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import java.util.Vector;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;

public class DisplayEmpData extends JFrame implements ActionListener {

    JFrame frame1;
    JLabel l0, l1, l2;
    JComboBox c1;
    JButton b1;
    Connection con;
    ResultSet rs, rs1;
    Statement st, st1;
    PreparedStatement pst;
    String ids;
    static JTable table;
    String[] columnNames = {"User name", "Email", "Password", "Country"};
    String from;

    DisplayEmpData() {

        l0 = new JLabel("Fatching Employee Information");
        l0.setForeground(Color.red);
        l0.setFont(new Font("Serif", Font.BOLD, 20));
        l1 = new JLabel("Select name");
        b1 = new JButton("submit");

        l0.setBounds(100, 50, 350, 40);
        l1.setBounds(75, 110, 75, 20);
        b1.setBounds(150, 150, 150, 20);
        b1.addActionListener(this);

        setTitle("Fetching Student Info From DataBase");
        setLayout(null);
        setVisible(true);
        setSize(500, 500);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        add(l0);
        add(l1);;
        add(b1);
        try {
            Class.forName("com.mysql.jdbc.Driver");  // (1)
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/db_name", "username", "password");  // (2)
            st = con.createStatement();
            rs = st.executeQuery("select uname from emp");
            Vector v = new Vector();
            while (rs.next()) {
                ids = rs.getString(1);
                v.add(ids);
            }
            c1 = new JComboBox(v);
            c1.setBounds(150, 110, 150, 20);

            add(c1);
            st.close();
            rs.close();
        } catch (Exception e) {
        }
    }

    public void actionPerformed(ActionEvent ae) {
        if (ae.getSource() == b1) {
            showTableData();
        }

    }

    public void showTableData() {

        frame1 = new JFrame("Database Search Result");
        frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame1.setLayout(new BorderLayout());
//TableModel tm = new TableModel();
        DefaultTableModel model = new DefaultTableModel();
        model.setColumnIdentifiers(columnNames);
//DefaultTableModel model = new DefaultTableModel(tm.getData1(), tm.getColumnNames());
//table = new JTable(model);
        table = new JTable();
        table.setModel(model);
        table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
        table.setFillsViewportHeight(true);
        JScrollPane scroll = new JScrollPane(table);
        scroll.setHorizontalScrollBarPolicy(
                JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        scroll.setVerticalScrollBarPolicy(
                JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
        from = (String) c1.getSelectedItem();
//String textvalue = textbox.getText();
        String uname = "";
        String email = "";
        String pass = "";
        String cou = "";

        try {
            pst = con.prepareStatement("select * from emp where UNAME='" + from + "'");
            ResultSet rs = pst.executeQuery();
            int i = 0;
            if (rs.next()) {
                uname = rs.getString("uname");
                email = rs.getString("umail");
                pass = rs.getString("upass");
                cou = rs.getString("ucountry");
                model.addRow(new Object[]{uname, email, pass, cou});
                i++;
            }
            if (i < 1) {
                JOptionPane.showMessageDialog(null, "No Record Found", "Error", JOptionPane.ERROR_MESSAGE);
            }
            if (i == 1) {
                System.out.println(i + " Record Found");
            } else {
                System.out.println(i + " Records Found");
            }
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
        }
        frame1.add(scroll);
        frame1.setVisible(true);
        frame1.setSize(400, 300);
    }

    public static void main(String args[]) {
        new DisplayEmpData();
    }
}
import java.awt.*;
导入java.awt.event.*;
导入java.sql.*;
导入java.util.Vector;
导入javax.swing.*;
导入javax.swing.table.DefaultTableModel;
公共类DisplayEmpData扩展JFrame实现ActionListener{
jframe1;
JLabel l0,l1,l2;
JComboBox c1;
按钮b1;
连接con;
结果集rs,rs1;
报表st、st1;
编制报表pst;
字符串ID;
静态JTable表;
String[]columnNames={“用户名”、“电子邮件”、“密码”、“国家”};