Issue
I've been trying to set up my own rest api for a school project. I decided to use MySQL as a database and i want to connect it with my webservice, but apparently i always get this error message: java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/userdatenbank
When i look at the error message, it also tells me that this code can't be executed:
public UserService() {
try {
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/userdatenbank", "root", "adminadmin123");
} catch (SQLException e) {
e.printStackTrace();
}
}
I don't know why this keeps happening... The MySQL Java Connector JAR-File is located in "Referenced Libraries". By the way I use Tomcat 9, MySQL 8, JDK 13 and Maven (Jersey Servlet).
Solution
Before get connection you have to load your driver with:
Class.forName("com.mysql.jdbc.Driver");
And the corresponding JAR must be in your classpath (in the lib of your server or packaged in your WAR file).
Anyway I suggest you to use a connection's pool instead of DriverManager
The main benefits to connection pooling are:
- Reduced connection creation time.
Although this is not usually an issue with the quick connection setup that MySQL offers compared to other databases, creating new JDBC connections still incurs networking and JDBC driver overhead that will be avoided if connections are recycled.
- Simplified programming model.
When using connection pooling, each individual thread can act as though it has created its own JDBC connection, allowing you to use straightforward JDBC programming techniques.
- Controlled resource usage.
If you create a new connection every time a thread needs one rather than using connection pooling, your application's resource usage can be wasteful, and it could lead to unpredictable behaviors for your application when it is under a heavy load.
Answered By - Renato