java - 从数据库中检索信息并将其显示在文本框或JTable中

时间:2016-09-29 08:19:33

标签: java database swing resultset

实际上,这是我的代码的一小部分,允许用户通过名称搜索名为" Artists"的数据库。如何将检索到的信息显示在JTable中?

private void btnSearchActionPerformed(java.awt.event.ActionEvent evt) {                                          
    // TODO add your handling code here:
    try {
        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");/* loads the jdbcodbc driver not using username and password */
        Connection connect = DriverManager.getConnection("jdbc:odbc:artist");
        Statement state = connect.createStatement();/* Gets a statement */
        String query = "SELECT * FROM Artists "+ "WHERE Name = '" + txtName.getText() + "'";
        ResultSet results = state.executeQuery(query);/* Result set returned for a query */
        if (!results.next()) {
            System.out.println("Name is incorrect");
            throw new WrongNameException();/* Exception thron if information is incorrect*/

        } else {
            System.out.println("You have successfully Searched!");

        }
        state.close();
    } catch(SQLException | ClassNotFoundException | WrongNameException e) { /* catches the exceptions */
        JOptionPane.showMessageDialog(null,e,"Error ",0);
    }
} 

2 个答案:

答案 0 :(得分:1)

从SQL查询中获取数据

String data1 = data1;
String data2 = data2;
String data3 = data3;
String data4 = data4;

Object[] row = { data1, data2, data3, data4 };

DefaultTableModel model = (DefaultTableModel) jTable1.getModel();

model.addRow(row);

答案 1 :(得分:0)

我遇到了类似的问题并将其修复到类似的项目上。我将为您提供一个指向我的GitHub代码的链接,确保您不只是复制并粘贴它,并期望它运行。请修改包名称,数据库连接和其他代码(如表名(getter和setter))以检索所需的结果。如果您想要任何帮助来编辑此代码,请随时回复,我会尽快回复您。

代码链接:

https://github.com/milanconhye/TechMart/blob/master/TechMart_1.3/src/TechMart/Catalogue.java