查询并把查询结果显示Jframe上的代码
时间: 2024-01-01 21:06:06 浏览: 58
查询数据库并在 JFrame 上显示结果的代码示例如下:
```
import java.awt.BorderLayout;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
public class DatabaseTable extends JFrame {
private static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
private static final String DB_URL = "jdbc:mysql://localhost:3306/mydatabase";
private static final String USERNAME = "root";
private static final String PASSWORD = "password";
private Connection conn = null;
private Statement stmt = null;
private ResultSet rs = null;
private JTable table;
public DatabaseTable() {
try {
// Register JDBC driver
Class.forName(JDBC_DRIVER);
// Open a connection
conn = DriverManager.getConnection(DB_URL, USERNAME, PASSWORD);
// Execute query
stmt = conn.createStatement();
String sql = "SELECT * FROM mytable";
rs = stmt.executeQuery(sql);
// Create JTable with ResultSet
table = new JTable(buildTableModel(rs));
// Add JTable to JFrame
JScrollPane scrollPane = new JScrollPane(table);
getContentPane().add(scrollPane, BorderLayout.CENTER);
// Set frame properties
setTitle("Database Table");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(600, 400);
setLocationRelativeTo(null);
setVisible(true);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// Close ResultSet, Statement, Connection
rs.close();
stmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
new DatabaseTable();
}
// Helper method to build JTable from ResultSet
public static JTable buildTableModel(ResultSet rs) {
try {
// Get metadata of ResultSet
int columnCount = rs.getMetaData().getColumnCount();
// Create array of column names
String[] columnNames = new String[columnCount];
for (int i = 1; i <= columnCount; i++) {
columnNames[i-1] = rs.getMetaData().getColumnName(i);
}
// Create array of row data
Object[][] rowData = new Object[0][columnCount];
while (rs.next()) {
Object[] newRow = new Object[columnCount];
for (int i = 1; i <= columnCount; i++) {
newRow[i-1] = rs.getObject(i);
}
rowData = addRow(rowData, newRow);
}
// Create JTable with column names and row data
JTable table = new JTable(rowData, columnNames);
return table;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
// Helper method to add row to array of row data
public static Object[][] addRow(Object[][] rowData, Object[] newRow) {
Object[][] result = new Object[rowData.length + 1][];
System.arraycopy(rowData, 0, result, 0, rowData.length);
result[rowData.length] = newRow;
return result;
}
}
```
在这个示例中,我们使用了 MySQL 数据库,并从一个名为 `mytable` 的表中检索了所有数据。然后,我们将结果集用 `buildTableModel()` 方法转换为 JTable,并将其添加到 JFrame 中显示。最后,我们关闭了结果集、语句和连接。你可以根据自己的需要进行修改。
阅读全文