user1950221
user1950221

Reputation: 13

Java Servlet & MySQL

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?

Upvotes: 0

Views: 65

Answers (2)

kgautron
kgautron

Reputation: 8263

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.

Upvotes: 1

Asaph
Asaph

Reputation: 162771

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.

Upvotes: 1

Related Questions