我正在尝试使用 java 查询数据库,我不明白这个函数的问题。它返回垃圾值。
我只想从 MySQL 数据库中检索与 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")));
}
最佳答案
您可以使用两种方式,第一种是将您的查询与您要搜索的 first_name 连接起来:
"SELECT id, first_name, last_name FROM customers WHERE first_name= '" + cusDB + "'"
第二次使用 PrepapredStatement
像这样:
"SELECT id, first_name, last_name FROM customers WHERE first_name= ?"
st.setString(1, cusDB);
但是我没有看到任何关于 PrepapredStatement 的迹象,所以你可以在这里学习 Prepared Statement doc
编辑
正如@André Schild 在评论中所说:
您容易受到 SQL 注入(inject)攻击,例如带有 ' 的名字;从客户中删除;//将从您的数据库中删除所有客户
。始终(tm)使用准备好的语句
关于java - Mysql DB select from table where字段语句java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42244885/