1

I'm trying to query database using java, I don't understand the problem with this function. it return a garbage values.

I just want to retrieve from a MySQL database the values matching the first_name.

public List<Customer> select(String cusDB) {
    return jdbcTemplate.query(
            "SELECT id, first_name, last_name FROM customers WHERE first_name= cusDB",
            (rs, rowNum) -> new Customer(rs.getLong("id"),
                    rs.getString("first_name"), rs.getString("last_name")));
}
1
  • I'd be very surprised if this would return "garbage values", I'd sooner expect an exception about an unknown column cusDB or something like that. Commented Feb 15, 2017 at 10:03

2 Answers 2

3

You can use two ways the first is to concatinate your query with your first_name that you want to search:

"SELECT id, first_name, last_name FROM customers WHERE first_name= '" + cusDB + "'"

Second use PrepapredStatement like so :

"SELECT id, first_name, last_name FROM customers WHERE first_name= ?"
st.setString(1, cusDB);

But i don't see any sign about PrepapredStatement so you can learn here Prepared Statement doc

Edit

Like @André Schild said in the comment :

you are vulnerable to SQL injections, for example a firstname with '; delete from customers; //will remove all customers from your database. Always(tm) use prepared statements

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

2 Comments

Don't use the first version, you are vulnerable to SQL injections, for example a firstname with '; delete from customers; //will remove all customers from your database. Always(tm) use prepared statements
yes @AndréSchild for that i suggest to use PreparedStement, i think he miss some thing about String concatenation for that i post the first one thank you so much
1

You can't just have the name of a Java parameter in the query string. You need to provide the parameter to the query explicitly. To do this, change your code to:

public List<Customer> select(String cusDB) {
    return jdbcTemplate.query(
            "SELECT id, first_name, last_name FROM customers WHERE first_name= ?",
            new Object[] { cusDB },
            (rs, rowNum) -> new Customer(rs.getLong("id"),
                    rs.getString("first_name"), rs.getString("last_name")));
}

That is, you introduce a parameter placeholder (?) in the query string, and add an array of parameter values to the method call (one value for each parameter placeholder in your query). See also the JdbcTemplate documentation and documentation of JdbcTemplate.query(String sql, Object[] args, RowMapper<T> rowMapper).

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.