I'm pretty new to JAVA RESTful APIs, and now I'm trying to create one. I watched some tutorials, but the guy wasn't using database, he was only storing datas in an arraylist or sth at runtime.
I tried to make a database connection and then a simple query, and it works fine when I'm running it as a Java Application, but as soon as I try to use it inside my web-application, it cannot connect to my DB and throws an exception.
The exception:
SEVERE: Servlet.service() for servlet [Jersey Web Application] in context
with path [/restapi] threw exception [java.lang.IllegalStateException:
Cannot connect the database!] with root cause
java.sql.SQLException: No suitable driver found for
jdbc:mysql://localhost:3306/restapi?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
Here is my code, which works as a Java Application, but not in a webapp:
public class AuthService {
private String url = "jdbc:mysql://localhost:3306/restapi?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC";
public List<User> getAllUsers() {
List<User> users = new ArrayList<User>();
try (Connection conn = DriverManager.getConnection(url, "blabla", "blabla")) {
Statement stmt = conn.createStatement();
String sql;
sql = "SELECT * FROM users";
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
int id = rs.getInt("id");
String login = rs.getString("login");
String first = rs.getString("firstname");
String last = rs.getString("lastname");
users.add(new User(id, login, first, last));
}
} catch (SQLException e) {
throw new IllegalStateException("Cannot connect the database!", e);
}
return users;
}
Probably this won't be the correct way to connect to a DB (since I probably don't want to connect to the DB on every query), but it's not that important for me NOW.
(Sorry for my english, thanks for the answers.)