2

I am trying to print table values from database in Java. I have created connection successfully and was able to create a table as well. But I am having trouble with printing the table values.

try

        {

            Statement stmt = conn.createStatement();

            ResultSet rs;
            String getValues =
                    "SELECT * " + 
                    "FROM EMPLOYEE" /*+ this.tableName*/ + " ; ";
                    //this.executeUpdate(conn, getValues);

            rs = stmt.executeQuery(getValues);

            String printValues = rs.getString(???Want to print all the table values);


            System.out.println(printValues);


            System.out.println("Values Retrived");
        }
        catch (SQLException e)
        {
            System.out.println("ERROR: Could not get values from table");
            e.printStackTrace();
            return;
        }
    }

1 Answer 1

2

You will want to loop your result set using a while loop. Example below:

    public static ObservableList<Customer> search_ForDropDown(String searchQuery){
    MysqlDataSource dataSource = CurrentServer.getDataSource();
    ObservableList<Customer> data = FXCollections.observableArrayList();
    data.clear();

    try {
        String query = "SELECT * FROM CUSTOMER LIMIT 5";

        Connection conn = dataSource.getConnection();
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery(query);     

        while (rs.next()) {
            Customer customer = new Customer();
            customer.setID(rs.getInt("id"));
            customer.setPhoneNumber(rs.getString("phoneNumber"));
            customer.setEmailAddress(rs.getString("emailAddress"));

            data.add(customer);
        }

        rs.close();
        stmt.close();
        conn.close();

    } catch (SQLException e) {
        e.printStackTrace();
    }       
    return data;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Correct. I did end up using a loop. I read through the documentation of ResultSet. It points at a row of a table, so to go through each row, I would have to use a loop. It loops until there is a next() row and if there is then it prints out the values from the column of that row.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.