0

What's wrong with this code? It gives me "brand" = null.

public String getBrand(@WebParam(name = "regNr") String regNr) throws SQLException {

    String brand=null;
    Connection con;
    Statement st;
    ResultSet rs;

    String url = "jdbc:mysql://db4free.net:3606/cars";
    String user = "cars";
    String password = "";

    try {
        con = (Connection) DriverManager.getConnection(url, user, password);
        st = (Statement) con.createStatement();
        rs = st.executeQuery("SELECT * FROM Cars WHERE nr= '" + regNr + "'");

        if (rs.next()) {
            brand=rs.getString("brand");
        }


    } catch (SQLException ex) {

    }
    return brand;
}

I want to display the value of brand from database. Is it a problem with connection?

2 Answers 2

1

Either the query isn't returning any rows or a SQLException is being thrown. Add something to your catch block to discover what the exception is.

BTW: You should be calling close() on your ResultSet, Statement and Connection instances. I suggest putting those calls within a finally block. Additionally, your code is vulnerable to an attack called SQL injection. Use a PreparedStatement with parameters to repair this problem.

Sign up to request clarification or add additional context in comments.

2 Comments

There is an exception, but I'm not sure how to repair it
What is the value of ex->getMessage()?
1

There probably is an exception in the code but you don't see it because of the catch with nothing inside. Add a log of the exception inside it, to reveal the exception and see the problem.

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.