0

I got a method to get an integer from a MySQL table

public int getAddressID(String postcode) throws SQLException {
    String q = "SELECT PK_ADDRESS_ID FROM tbl_addresses WHERE postcode =" + "\"" + postcode + "\"";
    System.out.println(q);
    ResultSet rs = executeSearch(q);
    int pc = 0;
    while (rs.next()) {
        String str = rs.getString("postcode");
        pc = Integer.parseInt(str);
    }
    System.out.println(pc);
    return pc;
}

The query seems fine but somehow when I initialize some variable and use this method, I get the error Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "". Am I missing anything? Thanks for any help!

6
  • What is the value of postcode? Commented Nov 16, 2016 at 7:12
  • The idea is input a postcode and then find ADDRESS_ID. postcode value is unique. Commented Nov 16, 2016 at 7:14
  • if your return address_id value is not digit you can't convert to int. Commented Nov 16, 2016 at 7:16
  • @Ye Win: I think this points into the right direction. getString("postcode") tries to read postcode, but the query does not return it. Commented Nov 16, 2016 at 7:18
  • 1
    NOTE: Use a preparedStatement if you receive the postcode from an input. You are open to injection inserting a String like this into the query. Commented Nov 16, 2016 at 7:21

2 Answers 2

3

Your SQL is SELECT PK_ADDRESS_ID ...

but then you try to get

rs.getString("postcode");

change to

rs.getString("PK_ADDRESS_ID");
Sign up to request clarification or add additional context in comments.

Comments

-1

It seems you are selecting PK_ADDRESS_ID column from the database and the value returned is either "" (empty) or NULL. So it shows NumberFormatException which cannot be converted as a Number.

So please check the value you get from the database.

Comments

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.