Java swing 用JTable读取MySQL里的表数据代码示例
时间: 2024-03-23 08:38:29 浏览: 62
以下是一个简单的Java Swing应用程序示例,它使用JTable组件从MySQL数据库读取表数据:
```java
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class JTableExample extends JFrame {
private JTable table;
public JTableExample() {
setTitle("JTable Example");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(600, 400);
String[] header = {"ID", "Name", "Age", "City"};
DefaultTableModel model = new DefaultTableModel(header, 0);
table = new JTable(model);
JScrollPane pane = new JScrollPane(table);
add(pane);
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "root", "password");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM mytable");
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
String city = rs.getString("city");
Object[] row = {id, name, age, city};
model.addRow(row);
}
rs.close();
stmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
JTableExample example = new JTableExample();
example.setVisible(true);
}
}
```
在这个示例中,我们使用了MySQL的JDBC驱动程序来连接到数据库,并执行一个查询来检索表中的所有记录。然后,我们将结果添加到JTable中的DefaultTableModel对象中,并使用JScrollPane将表添加到应用程序的主窗口中。
阅读全文