I have a MySQL database (called database) with tables: event, gebruiker and situatie. Now I need to write code in Java (using netbeans) to test my restful webservice. I'm able to retrieve all users (=gebruikers, dutch), but when I want to retrieve one specific user by searching on it's primary key 'Username', I get this 500-error when testing the restful webservice. please help! this is my code in java:
@Stateless
@Path("gebruikers")
public class GebruikerService {
@Resource(name = "jdbc/socialebuurt")
private DataSource source;
/*
* Request all users.
*/
@GET
@Produces(MediaType.APPLICATION_JSON)
public List<Gebruiker> getGebruikers() {
try (Connection conn = source.getConnection()) {
try (PreparedStatement stat = conn.prepareStatement("SELECT * FROM gebruiker")) {
try (ResultSet rs = stat.executeQuery()) {
List<Gebruiker> results = new ArrayList<>();
while (rs.next()) {
Gebruiker g = new Gebruiker();
g.setUsername(rs.getString("Username"));
g.setNaam(rs.getString("Naam"));
g.setVoornaam(rs.getString("Voornaam"));
g.setStraat(rs.getString("Straat"));
g.setHuisNr(rs.getInt("huisnr"));
g.setPostcode(rs.getInt("postcode"));
g.setGemeente(rs.getString("gemeente"));
g.setWachtwoord(rs.getString("wachtwoord"));
results.add(g);
}
return results;
}
}
} catch (SQLException ex) {
throw new WebApplicationException(ex);
}
}
/*
* Request one specific user.
*/
@Path("{username}")
@GET
@Produces(MediaType.APPLICATION_JSON)
public Gebruiker getGebruiker(@PathParam("username") String username) {
try (Connection conn = source.getConnection()) {
try (PreparedStatement stat = conn.prepareStatement("SELECT * FROM gebruiker WHERE username = ?")) {
stat.setString(1,"");
try (ResultSet rs = stat.executeQuery()) {
if (rs.next()) {
Gebruiker ge = new Gebruiker();
ge.setUsername(rs.getString("Username"));
ge.setNaam(rs.getString("Naam"));
ge.setVoornaam(rs.getString("Voornaam"));
ge.setStraat(rs.getString("Straat"));
ge.setHuisNr(rs.getInt("huisnr"));
ge.setPostcode(rs.getInt("postcode"));
ge.setGemeente(rs.getString("gemeente"));
ge.setWachtwoord(rs.getString("wachtwoord"));
return ge;
} else {
throw new WebApplicationException(Status.NOT_FOUND);
}
}
}
} catch (SQLException ex) {
throw new WebApplicationException(ex);
}
}
}
Table 'gebruiker' has following attributes: username (primary key, varchar(26)), naam (text), voornaam (text), straat (text), huisNr (int(11)), postcode (int(4)), gemeente (text), wachtwoord (text). If more info is needed, please ask. Thanks to all!
您需要在语句中包含WHERE
子句,如下所示:
"SELECT * FROM gebruiker WHERE username =" + username;
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.