简体   繁体   中英

Mysql DB select from table where field statement java

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")));
}

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 '; delete from customers; //will remove all customers from your database '; delete from customers; //will remove all customers from your database . Always(tm) use prepared statements

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) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM