简体   繁体   中英

java - retrieving info from database and displaying it in textboxes or JTable

Baically, this is a small piece my code to allow the user to search the database called "Artists", for records via name. How would i display the information retrieved into a 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);
    }
} 

Get data from SQL query

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);

I have ran into a similar problem and fixed it on a similar project. I will be providing you to a link to my GitHub code, make sure you don't just copy and paste it, and expect it to run. Please modify the package name, and the database connection and other code such as table names (getters and setters) to retrieve the results you want. If you would like any help to edit this code, please feel free to reply and I will get back to you as soon as possible.

Link for code:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM