从 JDBC 数据库中检索数据到 Jtable

Retrieving Data from JDBC Database into Jtable

您好,我已成功将我的 jTable 链接到 JDBC 数据库。 但是,我无法检索它们。我希望在重新启动程序时显示已保存的数据,但它不起作用。

alarm.setText("");  
    DefaultTableModel model =(DefaultTableModel) hwList.getModel();
    if(!className.getText().trim().equals(""))
    {
        model.addRow(new Object[]{className.getText(), homeWork.getText(), dueDate.getText()});
    }
    else
    {
        alarm.setText("Class Name should not be blank.");
    }

        Connection conn;
        Statement st;

        try
    {
        String myDriver = "com.mysql.jdbc.Driver";
        String myUrl = "jdbc:mysql://localhost:3306/mysql";
        Class.forName("com.mysql.jdbc.Driver");
        System.out.println("Connecting to database");
        conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql", "root", "");
        System.out.println("Connected to databse");


        String a = className.getText();
        String b = homeWork.getText();
        String c = dueDate.getText();            

        System.out.println("Inserting into the table");
        st = conn.createStatement();
        String stmt="INSERT INTO hwList (className, homeWork, dueDate)"+ "VALUES ("+"\'"+a+"\',"+"\'"+b+"\',"+"\'"+c+"\')";
        System.out.println(stmt);
        st.executeUpdate(stmt);

        System.out.println("Saved!");

    }
    catch (Exception e)
    {
        System.err.println("Got an exception!");
        System.err.println(e.getMessage());
    }    

这是我保存文档的代码!

有什么方法可以在JDBC数据库中检索数据并通过Jtable显示出来吗? 很抱歉问了这么简单的问题,但我是 java 的新手,我迫切需要帮助!

非常感谢!

用于加载数据的代码...

顺便说一句,我的 jtable 是一个 3 列 table,其中三列分别是 className、homeWork、dueDate。 谢谢!

String sql="SELECT * FROM hwList";
ResultSet rs = st.executeQuery(sql);
while(rs.next())
{
    String d = rs.getString("className");
    String e = rs.getString("homeWork");
    String f = rs.getString("dueDate");
}

嘿,

  1. 将您的ResultSet更改为ArrayList
  2. 使用来自 ArrayList
  3. 的数据为您的 JTalbe 创建一个模型

应该可以。

String myDriver = "com.mysql.jdbc.Driver";
String myUrl = "jdbc:mysql://localhost:3306/mysql";
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Connecting to database");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql", "root", "");
System.out.println("Connected to databse");
Statement st;
Vector data = new Vector();
try {
    st = connection.createStatement();
    ResultSet res = st.executeQuery("SELECT col_name FROM table_name");
    ResultSetMetaData metaData = res.getMetaData();
    int columns = metaData.getColumnCount();
    while (res.next()) {
       Vector row = new Vector(columns);
       for (int i = 1; i <= columns; i++) {
        row.addElement(res.getObject(i));
       }
       data.addElement(row);
    }
} catch (SQLException e) {
    e.printStackTrace();
}
Vector columnNames = new Vector();
columnNames.addElement("col_1");
columnNames.addElement("col_name_n");
table = new JTable(data,columnNames);

您可以使用类似于上面的代码从数据库中检索数据并将其存储在 jtable 中。

首先创建一个新的 TableModel...

DefaultTableModel model = new DefaultTableModel(new String[]{"Class Name", "Home work", "Due Date"}, 0);

从数据库加载数据...

String sql="SELECT * FROM hwList";
ResultSet rs = st.executeQuery(sql);

将每一行数据添加到 table 模型...

while(rs.next())
{
    String d = rs.getString("className");
    String e = rs.getString("homeWork");
    String f = rs.getString("dueDate");
    model.addRow(new Object[]{d, e, f});
}

将模型应用于您的 JTable...

table.setModel(model);

您可能还想查看 The try-with-resources Statement 并确保您正确管理资源

首先创建 table 模型,然后使用 fetch_data() 函数。确保您的数据库连接正常。在主构造函数中调用函数。而已。

DefaultTableModel dm;

dm=(DefaultTableModel) jTable1.getModel();

public void fetch_data(){

    try{
        String sql= "select * from tbl_name";
        ResultSet rs=st.executeQuery(sql);
        YourjTableName.setModel(DbUtils.resultSetToTableModel(rs));
    }catch(Exception e){
        System.out.println(e);
    }
}

Step:1

import javax.swing.*;
import java.awt.*;
import javax.swing.table.DefaultTableModel;
import java.sql.*;
public class UserList extends JFrame {
    DefaultTableModel model = new DefaultTableModel();
    Container cnt = this.getContentPane();
    JTable jtbl = new JTable(model);
    public UserList() {
        cnt.setLayout(new FlowLayout(FlowLayout.LEFT));
        model.addColumn("Id");
        model.addColumn("Username");
        model.addColumn("Password");
        model.addColumn("Create");
        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection con = DriverManager.getConnection("jdbc:mysql://localhost/java_db", "root", "");
            PreparedStatement pstm = con.prepareStatement("SELECT * FROM users");
            ResultSet Rs = pstm.executeQuery();
            while(Rs.next()){
                model.addRow(new Object[]{Rs.getInt(1), Rs.getString(2),Rs.getString(3),Rs.getString(4)});
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        JScrollPane pg = new JScrollPane(jtbl);
        cnt.add(pg);
        this.pack();
    }
}

Step:2

import javax.swing.JFrame;
public class Main {
    public static void main(String[] args) {
        JFrame frame = new UserList();
        frame.setTitle("Swing Example");
        frame.setSize(500, 300);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

Demo

问题陈述: 从数据库中检索数据并显示在 java.

中的 JTable 上

代码:(用于检索) *根据需要更改代码

String tquery = "SELECT * FROM Member";
        DbConnection obj = new DbConnection();
        ResultSet r = obj.Retrive(tquery);
        while (r.next()) {
            int i = r.getInt(1);
            String d = r.getString(2);
            String e = r.getString(3);
            String f = r.getString(4);
            String h = r.getString(5);
            String w = r.getString(6);
            DefaultTableModel model = (DefaultTableModel) (Member_table.getModel());
            model.addRow(new Object[]{i, d, e, f, h, w});
        }

代码(简体):

        String tquery = "SELECT * FROM Member";
        ResultSet rs = st.executeQuery(sql);
        while (r.next()) {
            int i = r.getInt(1);
            String d = r.getString(2);
            DefaultTableModel model = (DefaultTableModel) (Member_table.getModel());
            model.addRow(new Object[]{i, d);//add row to JTable
        }

如果这样DefaultTableModel model = new DefaultTableModel(); 不工作使用 DefaultTableModel model = (DefaultTableModel) (Member_table.getModel());

希望对您有所帮助!