-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDatabaseTableViewer.java
More file actions
58 lines (47 loc) · 1.87 KB
/
Copy pathDatabaseTableViewer.java
File metadata and controls
58 lines (47 loc) · 1.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import javax.swing.*;1567
import javax.swing.table.DefaultTableModel;
import java.sql.*;
import java.awt.*;
public class DatabaseTableViewer extends JFrame {
// JDBC variables
static final String DB_URL = "jdbc:mysql://localhost:3306/your_database";
static final String USER = "your_username";
static final String PASS = "your_password";
public DatabaseTableViewer() {
// Set up JFrame
setTitle("Database Table");
setSize(600, 400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
// Create table model and table
DefaultTableModel model = new DefaultTableModel();
JTable table = new JTable(model);
try (Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM your_table")) {
// Get metadata to extract column names
ResultSetMetaData metaData = rs.getMetaData();
int columnCount = metaData.getColumnCount();
// Add column names to the table model
for (int i = 1; i <= columnCount; i++) {
model.addColumn(metaData.getColumnName(i));
}
// Add rows to the table model
while (rs.next()) {
Object[] rowData = new Object[columnCount];
for (int i = 1; i <= columnCount; i++) {
rowData[i - 1] = rs.getObject(i);
}
model.addRow(rowData);
}
} catch (SQLException e) {
e.printStackTrace();
}
// Add table to a scroll pane and add to frame
add(new JScrollPane(table), BorderLayout.CENTER);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
new DatabaseTableViewer().setVisible(true);
});
}
}