I'm making a rest API for an App I'm creating, I have a MySQL database and I'm using Springboot. I coded this
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import java.sql.ResultSet;
import java.sql.SQLException;
public class MySQLInfosGateway implements InfosGateway {
private NamedParameterJdbcTemplate jdbcTemplate;
public MySQLInfosGateway(NamedParameterJdbcTemplate jdbcTemplate){
this.jdbcTemplate=jdbcTemplate;
}
@Override
public Personne getInfos(String badge){
var query = "select NOM, PRENOM from PERSONNEL where BADGE = " badge;
var result = jdbcTemplate.query(query, new ResultSetExtractor<Object>() {
@Override
public Object extractData(ResultSet resultSet) throws SQLException, DataAccessException {
resultSet.next();
return new Personne(resultSet.getString("NOM"),resultSet.getString("PRENOM"));
}
});
return (Personne) result;
}
}
Here's my Personne
class :
package com.piroux.phoenixrhbackend.domain.entities;
public class Personne {
public String nom;
public String prenom;
public Personne(String nom, String prenom){
this.nom=nom;
this.prenom=prenom;
}
public String getPrenom() {
return prenom;
}
public String getNom() {
return nom;
}
public void setPrenom(String prenom) {
this.prenom = prenom;
}
public void setNom(String nom) {
this.nom = nom;
}
}
and I'm trying with the following request on Postman:
localhost:8080/fonction-recup-infos/nom-prenom?badge=50387
If I execute the request select NOM, PRENOM from PERSONNEL where **BADGE** = 50387
- In a SQL script => I get the correct
NOM
andPRENOM
; - With my API => I get
null
andnull
For you to know, BADGE
is a unique String, qo there's only one NOM and PRENOM for each BADGE.
It's my first time creating a REST API so if any information is missing please tell me
CodePudding user response:
Change this line from
var query = "select NOM, PRENOM from PERSONNEL where BADGE = " badge;
to
var query = "select NOM, PRENOM from PERSONNEL where BADGE = '" badge "'";
It might be resolved.
CodePudding user response:
A couple of things wrong with your code. First never use concatenation to create a query string based on user input. It is dangerous. Second I would suggest using the RowMapper
instead of the ResultSetExtractor
it is easier to use.
You are using getString("<column-name>")
if your database doesn't expose the metadata this won't work and you have to use positional identifiers.
All in all I suggest you do this.
@Override
public Personne getInfos(String badge){
var query = "select NOM, PRENOM from PERSONNEL where BADGE = ?";
var result = jdbcTemplate.queryForObject(query, (rs, row) ->
new Personne(rs.getString("NOM"), rs.getString("PRENOM"), badge);
return result;
}
NOTE: You also might want to try nom
and prenom
as the column names, yuo are using MySQL which can be a bit picky about casing (depending on your configuration of MySQL and the platform you are running on).