简体   繁体   中英

java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/database

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).

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:

  1. 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.

  1. 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.

  1. 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.

Since you are using maven just add the dependency in your pom.xml file.

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.37</version>

Just go to the maven repo and search for a version that works for you. or If you have downloaded the jar file then add it to your project classpath.

edit -> Class.forName() is not needed since JDBC 4.0.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM