我有下面的代码,运行时得到以下错误。似乎有一些问题 String
到 VARCHAR
转换。
curl -v localhost:8080/trainer/Rach
* Trying ::1...
* TCP_NODELAY set
* Connected to localhost (::1) port 8080 (#0)
> GET /trainer/Rach HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.55.1
> Accept: */*
>
< HTTP/1.1 500
< Content-Type: application/json
< Transfer-Encoding: chunked
< Date: Wed, 17 Jun 2020 12:43:21 GMT
< Connection: close
<
{"timestamp":"2020-06-17T12:43:21.205+0000","status":500,"error":"Internal Server Error","message":"StatementCallback; bad SQL grammar [SELECT * fr
om TRAINERS where NAME=Rach]; nested exception is org.h2.jdbc.JdbcSQLSyntaxErrorException: Column \"RACH\" not found; SQL statement:\nSELECT * from
TRAINERS where NAME=Rach [42122-200]","path":"/trainer/Rach"}* Closing connection 0
@GetMapping("/trainer/{trainer_name}")
public Trainer getTrainer(@PathVariable String trainer_name) {
Trainer t = jdbcTemplate.queryForObject("SELECT * from TRAINERS where NAME=" + trainer_name , new
TrainerRawMapper());
return t;
}
public class TrainerRawMapper implements RowMapper<Trainer> {
@Override
public Trainer mapRow(ResultSet rs, int rowNum) throws SQLException {
Trainer trainer = new Trainer();
trainer.setName(rs.getString("NAME"));
trainer.setLevel(rs.getInt("LEVEL"));
trainer.setBag(new Stack<Pokemon>());
return trainer;
}
}
CREATE TABLE TRAINERS (NAME VARCHAR(225) PRIMARY KEY,
LEVEL INT)
-- TRAINERS insertions
INSERT INTO TRAINERS (NAME,LEVEL) VALUES ('Rach',8);
INSERT INTO TRAINERS (NAME,LEVEL) VALUES ('Rache',0);
INSERT INTO TRAINERS (NAME,LEVEL) VALUES ('Rachel',1);
INSERT INTO TRAINERS (NAME,LEVEL) VALUES ('Racheli',2);
更新查询,并将 trainer_name
不加引号,像这样。
String sql = "SELECT * from TRAINERS where NAME = '" + trainer_name +"'";
Trainer t = jdbcTemplate.queryForObject(sql, new TrainerRawMapper());
解决的办法只是纠正错误的地方。
, 出于安全考虑 最好使用jdbcTemplate来替换值,以避免SQL注入等SQL攻击。
String sql = "SELECT * from TRAINERS where NAME = ?";
return jdbcTemplate.queryForObject(sql, new Object[]{trainer_name}, new TrainerRawMapper());
主要问题是你使用String concat来产生查询,这是非常危险的,在这种情况下会导致一个错误的查询。值没有被转义,因此是一个无效的查询。你应该做的是使用正确的JDBC机制来替换查询中的值。
String query = "SELECT * from TRAINERS where NAME=?"
return jdbcTemplate.queryForObject(query, new TrainerRawMapper(), trainer_name);
现在,查询将被正确执行,你也可以避免SQL注入攻击。附加的好处是,当再次执行时,查询可能会被缓存,从而导致性能提升。