Меню

No suitable driver found for jdbc mysql ошибка

Using Java, I get this error when attempting to connect to a mysql database:

java.sql.SQLException: No suitable driver found for 
jdbc:mysql://localhost:3306/mysql at
java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at MyTest1.main(MyTest1.java:28)

I’m using the mysql-connector-java-5.1.18-bin.jar driver. It is in my build path. I have restarted MySQL. I’ve also logged on from the command line with root and no password and it connected fine. I’m not currently seeing a port 3306 in netstat. Previously I was getting a different error (I didn’t change the code). The error was «jdbc mysql Access denied for user ‘root’@’localhost password NO»

try {
    Class.forName("com.mysql.jdbc.Driver");
} 
catch (ClassNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} 


try {
    String url = "jdbc:mysql://localhost:3306/mysql";
    Connection con = DriverManager.getConnection(url, "root", "");
}
catch (Exception e){
    e.printStackTrace();
}

OneCricketeer's user avatar

OneCricketeer

168k18 gold badges124 silver badges229 bronze badges

asked Nov 16, 2011 at 4:37

user994165's user avatar

user994165user994165

8,96828 gold badges93 silver badges161 bronze badges

6

In this particular case (assuming that the Class#forName() didn’t throw an exception; your code is namely continuing with running instead of throwing the exception), this SQLException means that Driver#acceptsURL() has returned false for any of the loaded drivers.

And indeed, your JDBC URL is wrong:

String url = "'jdbc:mysql://localhost:3306/mysql";

Remove the singlequote:

String url = "jdbc:mysql://localhost:3306/mysql";

See also:

  • Mini tutorial on MySQL + JDBC connectivity

krock's user avatar

krock

28.5k13 gold badges77 silver badges85 bronze badges

answered Nov 16, 2011 at 5:43

BalusC's user avatar

BalusCBalusC

1.1m370 gold badges3584 silver badges3535 bronze badges

1

You have to set classpath for mysql-connector.jar

In eclipse, use the build path

If you are developing any web app, you have to put mysql-connector to the lib folder of WEB-INF Directory of your web-app

OneCricketeer's user avatar

OneCricketeer

168k18 gold badges124 silver badges229 bronze badges

answered Oct 6, 2012 at 17:51

prashant kumar's user avatar

3

When using Netbean, go under project tab and click the dropdown button there to select Libraries folder. Right Click on d Library folder and select ‘Add JAR/Folder’. Locate the mysql-connectore-java.*.jar file where u have it on ur system.
This worked for me and I hope it does for u too.
Revert if u encounter any problem

answered Dec 17, 2012 at 23:00

chibuzo nnonyelu's user avatar

This error happened to me, generally it’ll be a problem due to not including the mysql-connector.jar in your eclipse project (or your IDE).

In my case, it was because of a problem on the OS.

I was editing a table in phpmyadmin, and mysql hung, I restarted Ubuntu. I cleaned the project without being successful. This morning, when I’ve tried the web server, it work perfectly the first time.

At the first reboot, the OS recognized that there was a problem, and after the second one, it was fixed. I hope this will save some time to somebody that «could» have this problem!

Eric Leschinski's user avatar

answered Jan 27, 2013 at 10:11

xarlymg89's user avatar

xarlymg89xarlymg89

2,5122 gold badges27 silver badges40 bronze badges

A typographical error in the string describing the database driver can also produce the error.

A string specified as:

"jdbc:mysql//localhost:3307/dbname,"usrname","password"

can result in a «no suitable driver found» error. The colon following «mysql» is missing in this example.

The correct driver string would be:

jdbc:mysql://localhost:3307/dbname,"usrname","password"

MarsAtomic's user avatar

MarsAtomic

10.3k5 gold badges34 silver badges56 bronze badges

answered Mar 30, 2014 at 7:30

Karthick's user avatar

2

i had same problem i fix this using if developing jsp, put mysql connetor into WEB-INF->lib folder after puting that in eclipse right click and go build-path -> configure build patha in library tab add external jar file give location where lib folder is

answered Feb 9, 2014 at 2:59

hunter's user avatar

Just telling my resolution: in my case, the libraries and projects weren’t being added automatically to the classpath (i don’t know why), even clicking at the «add to build path» option. So I went on run -> run configurations -> classpath and added everything I needed through there.

answered Feb 12, 2015 at 20:25

Mr Guliarte's user avatar

Mr GuliarteMr Guliarte

7391 gold badge10 silver badges27 bronze badges

( If your url is correct and still get that error messege )
Do following steps to setup the Classpath in netbeans,

  1. Create a new folder in your project workspace and add the downloaded .jar file(eg:- mysql-connector-java-5.1.35-bin.jar )
  2. Right click your project > properties > Libraries > ADD jar/Folder
    Select the jar file in that folder you just make. And click OK.

Now you will see that .jar file will be included under the libraries. Now you will not need to use the line, Class.forName(«com.mysql.jdbc.Driver»); also.

If above method did not work, check the mysql-connector version (eg:- 5.1.35) and try a newer or a suitable version for you.

answered Jun 24, 2015 at 8:56

Malith's user avatar

MalithMalith

3816 silver badges18 bronze badges

The error «java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/test» occurs when you try to connect MySQL database running on your localhost, listening on port 3306 port from Java program but either you don’t have MySQL JDBC driver in your classpath or driver is not registered before calling the getConnection() method. Since JDBC API is part of JDK itself, when you write a Java program to connect any database like MySQL, SQL Server, or Oracle, everything compiles fine, as you only use classes from JDK but at runtime, when the JDBC driver which is required to connect to the database is not available, JDBC API either throws this error or «java.lang.ClassNotFoundException: com.mysql.jdbc.Driver».

The most common reason for this error is missing MySQL JDBC Driver JAR e.g. mysql-connector-java-5.0.8.jar not available in the classpath. Another common reason is you are not registering the driver before calling the getConnection() and you are running on Java version lower than 6 and not using a JDBC 4.0 compliant driver. We’ll see these reasons in more detail in this article.

Btw, if you are new to JDBC and looking for a comprehensive online course to learn JDBC in-depth then I also suggest you check out these Complete JDBC Programming course on Udemy. It’s a great course of direct classroom lectures and covers JDBC in depth

JAR not available in Classpath

If mysql-connector-java-5.0.8.jar is not available in classpath then you cannot connect to MySQL database from Java. Your program like below will compile fine but as soon as you will run it you will get the error «java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/test» because of the JDBC URL format «jdbc:mysql» is not matching with any registered JDBC driver.

Here is our Java program to demonstrate this error. This program reproduces this error by first leaving out the required JDBC JAR from the classpath and also not explicitly registering the driver before use by not calling the Class.forName() method.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

/*
 * Java Program to to connect to MySQL database and
 * fix java.sql.SQLException: No suitable driver found 
 * for jdbc:mysql://localhost:3306
 * error which occur if JAR is missing or you fail to register driver.
 */

public class Main {

  public static void main(String[] args) {

    Connection dbConnection = null;

    try {
      String url = "jdbc:mysql://localhost:3306/test";
      Properties info = new Properties();
      info.put("user", "root");
      info.put("password", "test");

      dbConnection = DriverManager.getConnection(url, info);

      if (dbConnection != null) {
        System.out.println("Successfully connected to MySQL database test");
      }

    } catch (SQLException ex) {
      System.out.println("An error occurred while connecting MySQL databse");
      ex.printStackTrace();
    }

  }

}

Output
An error occurred while connecting MySQL databse
java.sql.SQLException: No suitable driver found 
for jdbc:mysql://localhost:3306/test
at java.sql.DriverManager.getConnection(DriverManager.java:596)
at java.sql.DriverManager.getConnection(DriverManager.java:187) 

at Main.main(Main.java:24))

How to solve java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/

You need to do two things in order to solve this problem:

1) Add mysql-connector-java-5.0.8.jar or any other MySQL JAR corresponding to the MySQL database you are connecting. If you don’t have MySQL JDBC driver, you can download from here http://dev.mysql.com/downloads/connector/j/3.1.html

2) Add following line of code just before the call to Connection.getConnection(url, props) method

// load and register JDBC driver for MySQL
Class.forName("com.mysql.jdbc.Driver"); 

This will load the class, the JDBC driver to connect MySQL, com.mysql.jdbc.Driver from mysql-connector-java-5.0.8.jar and register it with JDBC API. Once you do that «java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/test» will go away.

Also, it’s worth noting that JDBC 4.0 released with Java SE 6 has now introduced auto-loading of JDBC driver class, which means you don’t need Class.forName(«com.mysql.jdbc.Driver»); any more, but only when you are running on at least Java 6 and your driver JAR is also JDBC 4.0 compliant

For example, the driver used in this program «mysql-connector-java-5.0.8.jar» is not JDBC 4.0 compliant, so even if you run this program in Java 6, 7 or Java 8, it will not work, but if you use mysql-connector-java-5.1.36.jar then even without adding «Class.forName(«com.mysql.jdbc.Driver»);», your program will work fine. Why? because JDBC will automatically load and register the driver, provided you have mysql-connector-java-5.1.36.jar file in your classpath. . See Core Java Volume 2 — Advanced features to learn more about new features introduces in JDBC 3.0 and JDBC 4.0 releases.

java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/test [Solution]

That’s all about how to solve «java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/test» error in Java program. This error occurs if JDBC is not able to find a suitable driver for the URL format passed to the getConnection() method e.g. «jdbc:mysql://» in our case. 

In order to solve this error, you need the MySQL JDBC driver like  mysql-connector-java-5.1.36.jar in your classpath. If you use a driver which is not JDBC 4.0 compliant then you also need to call the Class.forName(«com.mysql.jdbc.Driver») method to load and register the driver.

This error comes when you are trying to connect to MySQL database from Java program using JDBC but either the JDBC driver for MySQL is not available in the classpath or it is not registered prior to calling the DriverManager.getConnection() method. In order to get the connection to the database, you must first register the driver using the Class.forName() method. You should call this method with the correct name of the JDBC driver «com.mysql.jdbc.Driver» and this will both load and register the driver with JDBC. The type 4 JDBC driver for MySQL is bundled into MySQL connector JAR like mysql-connector-java-5.1.18-bin.jar depending upon which version of MySQL database you are connecting. 

Make sure this JAR is available in classpath before running your Java program, otherwise Class.forName() will not be able to find and load the class and throw java.lang.ClassNotFoundException: com.mysql.jdbc.Driver, another dreaded JDBC error, which we have seen in the earlier post.

Recently I have seen a common pattern of this error where a Java developer running his program on a version higher than Java SE 6 expects that JDBC driver’s JAR will be automatically loaded by JVM because of autoloading of JDBC driver feature of JDBC 4.0 released in JDK 6 but misses the trick that the JDBC driver should also be JDBC 4.0 compliant like  mysql-connector-java-5.1.18-bin.jar will be automatically loaded but older version may not, even if you run on Java 6. 

So, make sure you have both JDK 6 and a JDBC 4.0 compliant driver to leverage the auto-loading feature of JDBC 4.0 specification.  You can further see these free JDBC courses to learn more about JDBC 4.0 features.



How to reproduce the «No suitable driver found for ‘jdbc:mysql://localhost:3306/» Error in Java?

In order to better understand this error, let’s first reproduce this error by executing following Java program. I expect this program to throw the «No suitable driver found for ‘jdbc:mysql://localhost:3306/» error because I don’t have JDBC driver in the classpath.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/*
 * Java Program to to reproduce
 * java.sql.SQLException: No suitable driver found 
 * for jdbc:mysql://localhost:3306
 * error which occurs if MySQL JDBC Driver JAR is missing
 * or you not registering the JDBC driver before calling 
 * DriverManager.getConnection() method in JDBC.
 */

public class MySQLTest {

    public static void main(String[] args) throws ClassNotFoundException {

        Connection con = null;

        try {
            String url = "jdbc:mysql://localhost:3306/mysql";
            String username = "root";
            String password = "root";

            // Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection(url, username, password);

            if (con != null) {
                System.out
                        .println("Successfully connected to
                             MySQL database test");
            }

        } catch (SQLException ex) {
            System.out
                    .println("An error occurred while 
                           connecting MySQL databse");
            ex.printStackTrace();
        }

    }

}

Output
An error occurred while connecting MySQL databse
java.sql.SQLException: No suitable driver found 
for jdbc:mysql://localhost:3306/mysql
at java.sql.DriverManager.getConnection(DriverManager.java:596)
at java.sql.DriverManager.getConnection(DriverManager.java:215)

You can see that we got the «No suitable driver found» error in JDBC. The reason was that JDBC API couldn’t find any Driver corresponding to «jdbc:mysql://» URL because we have not added the MySQL connector JAR which contains the JDBC driver required to connect to MySQL database.

How to fix java.sql.SQLException: No suitable driver found for 'jdbc:mysql://localhost:3306/mysql

How to solve «No suitable driver found for jdbc:mysql://localhost:3306/mysql»

You can solve this problem first by adding MySQL connector JAR, which includes JDBC driver for MySQL into classpath e.g. mysql-connector-java-5.1.18-bin.jar. It’s very easy, just download the JAR from MySQL website and drop it into your classpath. For Example, if you are running in Eclipse then you can drop it on the root of your project folder. Same is true for Netbeans, but if you are running your Java program from the command prompt then either use -cp option or set the CLASSPATH as described here.

I prefer -cp option because it’s simple and easy and you can see what is included in classpath right in the command line itself, no need to worry about whether JAR is included in CLASSPATH environment variable or not.

java -cp mysql-connector-java-5.1.18-bin.jar:. MySQLTest

The error should go away just by adding JDBC driver in the classpath if you are running on Java 6, which supports JDBC 4.0 and the driver is also JDBC 4.0 compliant e.g. mysql-connector-java-5.1.36-bin.jar. From JDBC 4.0, Java has introduced auto loading of JDBC driver, hence you don’t need to load or register it manually using Class.forName() method.

If you are not running on Java SE 6 or your JDBC driver version doesn’t support JDBC 4.0 then just add the following line before calling DriverManager.getConnection() to load and register the MySQL JDBC driver. This will solve the problem (uncomment the line in above program):

Class.forName("com.mysql.jdbc.Driver");

This throws checked java.lang.ClassNotFoundException so makes sure you catch it. I have not caught it to keep the code clutter free by introducing try and catch statement.

So, in short:

1) Just add the MySQL JDBC JAR into classpath if you are running on Java SE 6 and driver is JDBC 4.0 compliant e.g. mysql-connector-java-5.1.36-bin.jar.

2) Alternatively, add the MySQL JDBC driver to classpath e.g. mysql-connector-java-5.1.18-bin.jar and call the Class.forName(«com.mysql.jdbc.Driver»); to load and register the driver before calling DriverManager.getConnection() method.

You can also check out JDBC API Tutorial and Reference (3rd Edition) to learn more about new features introduced in JDBC 3.0 and JDBC 4.0 specification and it is also one of the best books to learn JDBC API in Java.

How to solve No suitable driver found for 'jdbc:mysql://localhost:3306/mysql

That’s all about how to fix «No suitable driver found for jdbc:mysql://localhost:3306/mysql» error in Java. You can get this error from Eclipse or NetBeans IDE while connecting to local MySQL instance listening on default port 3306, don’t afraid, just follow the same approach. Drop the MySQL JDBC driver and call the Class.forName() method with the name of the class with implements Driver interface from JDBC API.

Related JDBC Tutorials for Java Programmers

  1. How to connect to MySQL database from Java Program (Guide)
  2. How to connect to Oracle database from Java (Guide)
  3. How to connect to Microsoft SQL Server from Java (Guide)
  4. How to setup JDBC connection Pool in Spring + Tomcat (Guide)
  5. 10 JDBC Best Practices Java Programmer Should Follow (see here)
  6. 6 JDBC Performance Tips for Java Applications (see here)

No suitable driver found for JDBC is an exception in Java that generally occurs when any driver is not found for making the database connectivity. In this section, we will discuss why we get such an error and what should be done to get rid of this exception so that it may not occur the next time.

No Suitable Driver Found For JDBC

Before discussing the exception, we should take a brief knowledge that what is a JDBC Driver.

What is a JDBC Driver

The JDBC (Java Database Connectivity) Driver is a driver that makes connectivity between a database and Java software. The JDBC driver can be understood as a driver that lets the database and Java application interact with each other. In JDBC, there are four different types of drivers that are to be used as per the requirement of the application. These JDBC divers are:

No Suitable Driver Found For JDBC

  1. JDBC-ODBC bridge driver
  2. Thin Layer driver
  3. Native API driver
  4. Network Protocol Driver

All four drivers have their own usage as well as pros and cons. To know more about JDBC Drivers, do visit: https://www.javatpoint.com/jdbc-driver section of our Java tutorial.

What is the Error and Why it Occurs?

Generally, «no suitable driver found» refers to throwing an error, i.e., «java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/test» in the console. The error occurs when we are trying to connect to the MySql (or any other) database that is existing on your local machine, i.e., localhost, and listens to the specified port number which is set for the mysql and it founds that either no JDBC driver was registered before invoking the DriverManager.getConnection () method or we might not have added the MySQL JDBC driver to the classpath in the IDE. In case we are running a simple Java code with no requirement of database connectivity, the Java API executes it correctly and well, but if there is the need for a JDBC driver, an error is thrown, which is the «class not found» error. In simple words, such an error is thrown when no suitable driver is found by the Java API so that it could connect the Java application to the database.

How to remove the error

Now the question is how to get rid of such error. In order to resolve the problem or error, one needs to add the MYSQL Connector JAR to the classpath because the classpath includes the JDBC Driver for the MYSQL through which the connection is generated between the Java code and the database. In order to add the MYSQL connector JAR file to the IDE or tool we are using, we need to go through some quite simple steps. These steps are as follows:

For Eclipse and NetBeans IDE

1) Open any internet browser on the system and search for MySQL Connector download in the search tab. Several downloading links will appear. Click on the MYSQL website https://www.mysql.com/products/connector/ from it and download the latest version of the MYSQL connector by selecting your system specs.

No Suitable Driver Found For JDBC

2) After the successful download of the MYSQL Connector, it will be seen at the default Downloads folder of your system, as you can see in the below snippet:

No Suitable Driver Found For JDBC

3) Now, open the IDE you are working upon, either NetBeans or Eclipse, and also any other tool/IDE, whichever you use. Here, we have used Eclipse IDE.

4) Go to your project and right-click on it. A list of options will appear. Select and click on Build Path > Configure Build Path, and the Java Build Path dialog box will open up, as you can see in the below snippet:

No Suitable Driver Found For JDBC

5) Click on Add External JARs and move to the location where you have downloaded the Mysql Connector, as you can see in the below snippet:

No Suitable Driver Found For JDBC

6) Select the Mysql Connector and click on Open. The JAR file will get added to your project build path, as you can see in the below snippet:

No Suitable Driver Found For JDBC

7) Click on Apply and Close, and the JDBC Driver will be added to your Eclipse IDE.

8) Run the JDBC connection code once again, and this time you will not get the «No suitable driver found for JDBC» exception instead of other errors if you made any other syntax problem.

9) The JDBC Driver will get connected successfully, and the connection will get established successfully.

Note: If you want to know how to make JDBC Connectivity in Java, visit https://www.javatpoint.com/example-to-connect-to-the-mysql-database

Point to be noted:

  • If you are using Java SE 6 with JDBC 4.0, then you may not require to load and register the driver because the new Java feature provides autoloading of the JDBC driver class. Due to which there is no requirement of using Class.forName(«com.mysql.jdbc.Driver»); statement. However, if the JDBC Jar you are using is old, i.e., JDBC 4.0 compliant with Java SE 6, then you may need to create this statement.
  • In brief, we can say that such an error occurs when no JDBC JAR file is added to the classpath of Java. Just we need to add the JAR file to the classpath and then execute the code. The code will hopefully get executed with success.

The java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/testdb exception occurs if the suitable driver is not found to connect mysql database from java application. The MySQL JDBC driver is not loaded in java either because the driver jar is not available in the class path, or because it is not possible to load the mysql driver jar. If no suitable driver is found in the java class path, the exception java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/testdb will be thrown.

The MySQL JDBC driver is used to connect your Java application to a MySQL database. The mysql driver sends the database query from java to the database. The Mysql database executes the query and returns the results. The MySQL JDBC driver receives the data from the MySQL database and sends it back to the Java application.

If the MySQL JDBC driver is not loaded, the Java program will throw the exception java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/testdb.

Exception

The stack trace of the exception will be shown as shown below. The exception java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/testdb  is due to the driver class not loaded in java.

Exception in thread "main" java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/testdb
	at java.sql.DriverManager.getConnection(DriverManager.java:689)
	at java.sql.DriverManager.getConnection(DriverManager.java:247)
	at com.yawintutor.DBConnection.main(DBConnection.java:13)

How to reproduce this exception

If the Java application can not load the MySQL JDBC driver class or the MySQL JDBC class is not available in the Java class path, the exception java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/testdb will be thrown. This exception will be reproduced in the example below.

package com.yawintutor;

import java.sql.Connection;
import java.sql.DriverManager;

public class DBConnection {
	public static void main(String[] args) throws Exception {
		String url = "jdbc:mysql://localhost:3306/testdb";
		String username = "root";
		String password = "root";

		Connection con = DriverManager.getConnection(url, username, password);
		if (con != null) {
			System.out.println("Database Connected successfully");
		} else {
			System.out.println("Database Connection failed");
		}
	}
}

Solution 1

If the MySQL JDBC driver jar is available in the class path and the driver class is unable to load, the driver class must be loaded in the java using class.forName() method. The forName() method will load the class from the fully qualified class name specified as an argument. The example below demonstrates how to load the MySQL JDBC driver class using the class.forName() method.

package com.yawintutor;

import java.sql.Connection;
import java.sql.DriverManager;

public class DBConnection {
	public static void main(String[] args) throws Exception {
		Class.forName("com.mysql.cj.jdbc.Driver");
		String url = "jdbc:mysql://localhost:3306/testdb";
		String username = "root";
		String password = "root";

		Connection con = DriverManager.getConnection(url, username, password);
		if (con != null) {
			System.out.println("Database Connected successfully");
		} else {
			System.out.println("Database Connection failed");
		}
	}
}

Solution 2

If you are using mysql database version till 5.x.x, the MySQL JDBC driver “com.mysql.cj.jdbc.Driver” will not be available. For the older mysql databases the driver class “com.mysql.jdbc.Driver” must be used. The java program will be as like below.

package com.yawintutor;

import java.sql.Connection;
import java.sql.DriverManager;

public class DBConnection {
	public static void main(String[] args) throws Exception {
		Class.forName("com.mysql.jdbc.Driver");
		String url = "jdbc:mysql://localhost:3306/testdb";
		String username = "root";
		String password = "root@123";

		Connection con = DriverManager.getConnection(url, username, password);
		if (con != null) {
			System.out.println("Database Connected successfully");
		} else {
			System.out.println("Database Connection failed");
		}
	}
}

Solution 3

If the MySQL JDBC driver jar is not available in the java class path, download the mysql driver jar from https://dev.mysql.com/downloads/connector/j/. The name of mysql driver jar is same as mysql-connector-java-8.0.20.jar. Add the jar to the java class path.

download the jar mysql-connector-java-8.0.20.jar from https://dev.mysql.com/downloads/connector/j/ 
( 
  goto https://dev.mysql.com/downloads/connector/j/
  select "Select Operating System:" as your operating system and install
      or
  select "Select Operating System:" as "Platform Independent", download the zip and extract
)

Add in your java project.

In eclipse
Right click in mysql-connector-java-8.0.20.jar -> Build Path -> Add to Build Path

Solution 4

If the java project is a maven project, add the mysql connector dependency in the pom.xml. The dependency will download the mysql-connector-java-8.0.22.jar in the repository and link to the project. The latest mysql connector dependency can be found in https://mvnrepository.com/artifact/mysql/mysql-connector-java

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

Solution 5

If the java project is build using the Gradle, add the dependency as below. When the project is build, the MySQL JDBC driver will be added to the java project.

dependencies {
    compile 'mysql:mysql-connector-java:8.0.22'
}

In this post, we will see how to resolve java.sql.SQLException: No suitable driver found for JDBC.

There can be multiple reasons for this exception and let’s see it one by one.

connector jar is not on classpath

you need make sure you have connector jar on classpath.

For example:
If you are using mysql to connect to database, then mysql-connector-java jar should on classpath.

You can add the maven dependency as below:

<! https://mvnrepository.com/artifact/mysql/mysql-connector-java —>

<dependency>

    <groupId>mysql</groupId>

    <artifactId>mysqlconnectorjava</artifactId>

    <version>8.0.19</version>

</dependency>

You can find versions of jar over here.

Jar not present in Tomcat/JBoss lib

If you are using web servers such as tomcat or JBoss, then you should put the connector jar in server lib folder.

For example:
In case you are using tomcat and mysql, you should put mysql-connector-java in $CATALINA_HOME/lib.

Actually, the connection pool needs to be set up before application is instantiated. This could be the reason, you need to put jar in server lib folder.

If you are using eclipse to run tomcat, then eclipse won’t pick $CATALINA_HOME/lib.
You can fix this issue in two ways:

  • Click on Open Launch Config -> classpath tab to set mysql-connector-java jar on classpath.
  • Go to server tab and select option Use Tomcat installation

Typo in connection url

This exception can also arise if you have typo in your jdbc url.

For example:
Let’s say if you have jdbc URL as below.

jdbc:mysql//localhost:3307/dbname

If you notice closely, we are missing : after mysql and URL should be

jdbc:mysql://localhost:3307/dbname

Did not call class.forName() [old java versions]

If you are using java version less than 6 or did not use JDBC 4.0 compliant connector jar, then you can get this exception.
You need to register driver before calling DriverManager.getConnection();

Let’s understand with the help of example:

Connection con = null;

try {

    con = DriverManager.getConnection(«jdbc:mysql//localhost:3307/dbname»);

} catch (SQLException e) {

    throw new RuntimeException(e);

}

Above code will give error because we did not call Class.forName() before calling DriverManager.getConnection().

You can fix the error with:

Connection con = null;

try {

    //registering the jdbc driver here

    Class.forName(«com.mysql.jdbc.Driver»);  

    con = DriverManager.getConnection(«jdbc:mysql//localhost:3307/dbname»);

} catch (SQLException e) {

    throw new RuntimeException(e);

}

If you are using Java 6 or above and the latest version of mysql-connector-java, then you should not get this exception because of Class.forName()

Conclusion

As you can see, there can be multiple reason for getting java.sql.SQLException: No suitable driver found for JDBC. You need to identify which can applicable in your application.

That’s all about how to fix no suitable driver found for jdbc error. If you are still facing this issue, please comment.

В этой статье мы научимся подключаться к базе данных MySQL из Java-кода и выполнять простые запросы для получения и обновления данных. Для того, чтобы получить доступ к базе данных, мы будем использовать JDBC (Java Database Connectivity) API, который входит в стандартную библиотеку Java. JDBC позволяет подключиться к любой базе данных: Postgres, MySQL, SQL Server, Oracle и т. д. — при наличии соответствующей реализации драйвера, необходимого для подключения. Для базы данных MySQL мы будем использовать драйвер Type 4 JDBC из пакета mysql-connector-java-5.1.23-bin.jar. Он написан на чистой Java, а значит, нам не понадобятся какие-либо нативные библиотеки или ODBC-мост. Все, что нам надо будет сделать — это положить JAR-файл в директорию, содержащуюся в CLASSPATH. JAR-файл содержит класс com.mysql.jdbc.Driver, необходимый для подключения к MySQL. Если его не окажется в CLASSPATH, во время выполнения программы выбросится исключение java.lang.ClassNotFoundException, поэтому убедитесь, что вы правильно настроили пути.

Кстати, если вы ищете хорошую книгу по использованию JDBC, обратите внимание на Practical Database Programming with Java (Ying Bai). Это относительно новая книга, и в ней рассматриваются две самые популярные базы данных: Oracle и SQL Server 2008. В книге используется IDE NetBeans для примеров и описываются все инструменты, необходимые для работы с базами данных в Java. Это отличная книга для начинающих и опытных программистов.

Подключаем базу данных MySQL с помощью JDBC

Для того, чтобы подключить базу данных MySQL, нам потребуется четыре вещи:

  1. Строка подключения JDBC (например:
    jdbc:mysql://localhost:3306/test).
  2. Имя пользователя (root).
  3. Пароль (root).
  4. База данных с некоторым количеством таблиц для примера (например, база данных книг).

Строка подключения для MySQL начинается с jdbc:mysql. Это название протокола соединения, за которым следуют хост и порт подключения, на которых запущена база данных. В нашем случае это localhost с портом по умолчанию 3306 (если вы его не поменяли при установке). Следующая часть — test — имя базы данных, которая уже существует в MySQL. Мы можем создать таблицу Books:

CREATE TABLE `books` (
  `id` int(11) NOT NULL,
  `name` varchar(50) NOT NULL,
  `author` varchar(50) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1

и наполнить её хорошими книгами:

INSERT INTO test.books (id, `name`, author)
    VALUES (1, 'Effective Java', 'Joshua Bloch');
INSERT INTO test.books (id, `name`, author)
    VALUES (2, 'Java Concurrency in Practice', 'Brian Goetz');

Программа на Java, которая использует базу данных

Теперь давайте напишем программу на Java, которая будет подключаться к нашей базе данных, запущенной на localhost. Важно помнить о том, что необходимо закрывать соединение, запросы и результат выполнения после завершения работы с ними. Также важно закрывать их в finally-блоке, со своей try/catch оберткой, поскольку сам метод close() может кинуть исключение, что приведет к утечке ресурсов. За подробной информацией вы можете обратиться к этой статье. Кроме того, вы можете использовать обертку try-with-resource, которая появилась в Java 7. Более того, это стандартный способ работы с ресурсами в Java 1.7.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * Simple Java program to connect to MySQL database running on localhost and
 * running SELECT and INSERT query to retrieve and add data.
 * @author Javin Paul
 */
public class JavaToMySQL {

    // JDBC URL, username and password of MySQL server
    private static final String url = "jdbc:mysql://localhost:3306/test";
    private static final String user = "root";
    private static final String password = "root";

    // JDBC variables for opening and managing connection
    private static Connection con;
    private static Statement stmt;
    private static ResultSet rs;

    public static void main(String args[]) {
        String query = "select count(*) from books";

        try {
            // opening database connection to MySQL server
            con = DriverManager.getConnection(url, user, password);

            // getting Statement object to execute query
            stmt = con.createStatement();

            // executing SELECT query
            rs = stmt.executeQuery(query);

            while (rs.next()) {
                int count = rs.getInt(1);
                System.out.println("Total number of books in the table : " + count);
            }

        } catch (SQLException sqlEx) {
            sqlEx.printStackTrace();
        } finally {
            //close connection ,stmt and resultset here
            try { con.close(); } catch(SQLException se) { /*can't do anything */ }
            try { stmt.close(); } catch(SQLException se) { /*can't do anything */ }
            try { rs.close(); } catch(SQLException se) { /*can't do anything */ }
        }
    }

}

При первом запуске у вас, возможно, будет ошибка No suitable driver found for jdbc:mysql, если драйвера MySQL нет в CLASSPATH:

java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/test/book
    at java.sql.DriverManager.getConnection(DriverManager.java:689)
    at java.sql.DriverManager.getConnection(DriverManager.java:247)
    at JavaToMySQL.main(JavaToMySQL.java:29)
Exception in thread "main" java.lang.NullPointerException
    at JavaToMySQL.main(JavaToMySQL.java:46)
Java Result: 1

Добавим нужный JAR-файл в путь и снова запустим программу. Другая частая ошибка — указать таблицу в строке соединения: jdbc:mysql://localhost:3306/test/book. В этом случае вылетит следущее исключение:

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown database 'test/book'
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance
(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance
(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:408)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
    at com.mysql.jdbc.Util.getInstance(Util.java:386)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1053)

Успешный запуск программы выведет на экран следующее:

Total number of books in the table: 2

Результат верный, поскольку у нас в таблице только две книги: «Effective Java» и «Java Concurrency in Practice».

Кстати, если у вас был драйвер при компиляции, но отсутствует при запуске, вы получите исключение java.lang.ClassNotFoundException: com.mysql.jdbc.Driver. О том, как исправить эту ошибку, вы можете прочитать здесь.

Получаем данные с помощью SELECT-запроса в JDBC

Для получения данных из БД вы можете выполнить SELECT-запрос. В первом примере мы уже его использовали, но получили только количество строк. Теперь мы вернем сами строки. Большая часть программы останется без изменений, за исключением SQL-запроса и кода, возвращающего данные из объекта ResultSet:

String query = "select id, name, author from books";

rs = stmt.executeQuery(query);

while (rs.next()) {
   int id = rs.getInt(1);
   String name = rs.getString(2);
   String author = rs.getString(3);
   System.out.printf("id: %d, name: %s, author: %s %n", id, name, author);
 }

Этот код выведет на экран следующее:

id: 1, name: Effective Java, author: Joshua Bloch
id: 2, name: Java Concurrency in Practice, author: Brian Goetz

Тут есть пара моментов, на которые следует обратить внимание. Метод rs.getInt(1) используется для получения столбца с целочисленным типом, в нашем случае это столбец «id». Индексы в JDBC начинаются с единицы, поэтому rs.getInt(1) вернет значение первого столбца как целое число. В случае, если вы укажете неверный индекс (многие разработчики вызывают rs.getInt(0) для получения первого столбца), выбросится исключение InvalidColumnIndexException. Доступ к столбцам по индексу чреват ошибками, поэтому лучше использовать имя столбца, например, rs.getInt("id"). Подробнее об этом вы можете прочитать в этой статье. Метод getString() используется для получения строковых значений из базы (например, VARCHAR). Цикл будет выполняться, пока rs.next() не вернет false. Это значит, что строки закончились. В нашем случае в таблице две строки, поэтому цикл выполнится два раза, выводя информацию о книгах из таблицы на экран.

Добавляем данные с помощью INSERT-запроса в JDBC

Добавление данных мало отличается от их получения: мы просто используем INSERT-запрос вместо SELECT-запроса и метод executeUpdate() вместо executeQuery(). Этот метод используется для запросов INSERT, UPDATE и DELETE, а также для SQL DDL выражений, таких как CREATE, ALTER или DROP. Эти команды не возвращают результата, поэтому мы убираем все упоминания ResultSet‘а в коде и изменяем запрос соответственно:

String query = "INSERT INTO test.books (id, name, author) n" +
               " VALUES (3, 'Head First Java', 'Kathy Sieara');";

// executing SELECT query
stmt.executeUpdate(query);

После запуска программы вы можете проверить таблицу в СУБД. На этот раз вы увидите три записи в таблице:

Connecting MySQL Database from Java

Теперь вы умеете подключаться к MySQL из Java-приложения и выполнять SELECT, INSERT, DELETE и UPDATE-запросы так же, как и в MySQL GUI. Для подключения мы используем объект Connection, для чтения результатов запроса — ResultSet. Убедитесь перед подключением, что сервер MySQL запущен и mysql-connector-java-5.1.17-bin.jar находится в CLASSPATH, чтобы избежать ClassNotFoundException.

Когда разберетесь с подключением и простыми запросами, имеет смысл изучить, как использовать подготавливаемые запросы (Prepared Statement) в Java для избежания SQL-инъекции. В боевом коде всегда следует использовать подготавливаемые запросы и связывание переменных.

Если вам понравилось это руководство и не терпится узнать больше о подключении и работе с базой данных из Java-программ, обратите внимание на следующие статьи:

  • Как подключиться к БД Oracle из Java-приложения;
  • Отличия межу Connected RowSet и Disconnected RowSet в Java;
  • Как использовать пул соединений в Spring;
  • 5 способов улучшить производительность БД в приложениях на Java;
  • Отличия между java.util.Date и java.sql.Date в Java;
  • Как выполнить INSERT или UPDATE, используя пакетные запросы JDBC;
  • Десять вопросов по JDBC на собеседованиях.

Полезные ссылки

  • Если у вас нет базы данных MySQL, вы можете ее скачать здесь;
  • Есди у вас нет драйвера MySQL для JDBC, вы можете скачать его отсюда;
  • Рекомендованную книгу «Practical Database Programming with Java» можно купить на Amazon.

Перевод статьи «How to Connect to MySQL database in Java with Example»

I’m trying to add a database-enabled JSP to an existing Tomcat 5.5 application (GeoServer 2.0.0, if that helps).

The app itself talks to Postgres just fine, so I know that the database is up, user can access it, all that good stuff. What I’m trying to do is a database query in a JSP that I’ve added. I’ve used the config example in the Tomcat datasource example pretty much out of the box. The requisite taglibs are in the right place — no errors occur if I just have the taglib refs, so it’s finding those JARs. The postgres jdbc driver, postgresql-8.4.701.jdbc3.jar is in $CATALINA_HOME/common/lib.

Here’s the top of the JSP:

<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<sql:query var="rs" dataSource="jdbc/mmas">
  select current_validstart as ValidTime from runoff_forecast_valid_time
</sql:query>

The relevant section from $CATALINA_HOME/conf/server.xml, inside the <Host> which is in turn within <Engine>:

<Context path="/gs2" allowLinking="true">
  <Resource name="jdbc/mmas" type="javax.sql.Datasource"
      auth="Container" driverClassName="org.postgresql.Driver"
      maxActive="100" maxIdle="30" maxWait="10000"
      username="mmas" password="very_secure_yess_precious!"
      url="jdbc:postgresql//localhost:5432/mmas" />
</Context>

These lines are the last in the tag in webapps/gs2/WEB-INF/web.xml:

<resource-ref>
  <description>
     The database resource for the MMAS PostGIS database
  </description>
  <res-ref-name>
     jdbc/mmas
  </res-ref-name>
  <res-type>
     javax.sql.DataSource
  </res-type>
  <res-auth>
     Container
  </res-auth>
</resource-ref>

Finally, the exception:

   exception
    org.apache.jasper.JasperException: Unable to get connection, DataSource invalid: "java.sql.SQLException: No suitable driver"
    [...wads of ensuing goo elided]

BalusC's user avatar

BalusC

1.1m370 gold badges3584 silver badges3535 bronze badges

asked Dec 15, 2009 at 23:33

Rick Wayne's user avatar

1

The infamous java.sql.SQLException: No suitable driver found

This exception can have basically two causes:

1. JDBC driver is not loaded

In case of Tomcat, you need to ensure that the JDBC driver is placed in server’s own /lib folder.

Or, when you’re actually not using a server-managed connection pool data source, but are manually fiddling around with DriverManager#getConnection() in WAR, then you need to place the JDBC driver in WAR’s /WEB-INF/lib and perform ..

Class.forName("com.example.jdbc.Driver");

.. in your code before the first DriverManager#getConnection() call whereby you make sure that you do not swallow/ignore any ClassNotFoundException which can be thrown by it and continue the code flow as if nothing exceptional happened. See also Where do I have to place the JDBC driver for Tomcat’s connection pool?

Other servers have a similar way of placing the JAR file:

  • GlassFish: put the JAR file in /glassfish/lib
  • WildFly: put the JAR file in /standalone/deployments

2. Or, JDBC URL is in wrong syntax

You need to ensure that the JDBC URL is conform the JDBC driver documentation and keep in mind that it’s usually case sensitive. When the JDBC URL does not return true for Driver#acceptsURL() for any of the loaded drivers, then you will also get exactly this exception.

In case of PostgreSQL it is documented here.

With JDBC, a database is represented by a URL (Uniform Resource Locator). With PostgreSQL™, this takes one of the following forms:

  • jdbc:postgresql:database
  • jdbc:postgresql://host/database
  • jdbc:postgresql://host:port/database

In case of MySQL it is documented here.

The general format for a JDBC URL for connecting to a MySQL server is as follows, with items in square brackets ([ ]) being optional:

jdbc:mysql://[host1][:port1][,[host2][:port2]]...[/[database]] » [?propertyName1=propertyValue1[&propertyName2=propertyValue2]...]

In case of Oracle it is documented here.

There are 2 URL syntax, old syntax which will only work with SID and the new one with Oracle service name.

Old syntax jdbc:oracle:thin:@[HOST][:PORT]:SID

New syntax jdbc:oracle:thin:@//[HOST][:PORT]/SERVICE


See also:

  • Where do I have to place the JDBC driver for Tomcat’s connection pool?
  • How to install JDBC driver in Eclipse web project without facing java.lang.ClassNotFoundexception
  • How should I connect to JDBC database / datasource in a servlet based application?
  • What is the difference between «Class.forName()» and «Class.forName().newInstance()»?
  • Connect Java to a MySQL database

answered Dec 16, 2009 at 0:28

BalusC's user avatar

BalusCBalusC

1.1m370 gold badges3584 silver badges3535 bronze badges

6

I’ve forgot to add the PostgreSQL JDBC Driver into my project (Mvnrepository).

Gradle:

// http://mvnrepository.com/artifact/postgresql/postgresql
compile group: 'postgresql', name: 'postgresql', version: '9.0-801.jdbc4'

Maven:

<dependency>
    <groupId>postgresql</groupId>
    <artifactId>postgresql</artifactId>
    <version>9.0-801.jdbc4</version>
</dependency>

You can also download the JAR and import to your project manually.

answered Jul 17, 2018 at 14:25

Manuel Schmitzberger's user avatar

url="jdbc:postgresql//localhost:5432/mmas"

That URL looks wrong, do you need the following?

url="jdbc:postgresql://localhost:5432/mmas"

answered Dec 15, 2009 at 23:56

araqnid's user avatar

araqnidaraqnid

123k23 gold badges153 silver badges133 bronze badges

I faced the similar issue.
My Project in context is Dynamic Web Project(Java 8 + Tomcat 8) and error is for PostgreSQL Driver exception: No suitable driver found

It got resolved by adding Class.forName("org.postgresql.Driver") before calling getConnection() method

Here is my Sample Code:

try {
            Connection conn = null;
            Class.forName("org.postgresql.Driver");
            conn = DriverManager.getConnection("jdbc:postgresql://" + host + ":" + port + "/?preferQueryMode="
                    + sql_auth,sql_user , sql_password);
        } catch (Exception e) {
            System.out.println("Failed to create JDBC db connection " + e.toString() + e.getMessage());
        }

Faysal Ahmed's user avatar

Faysal Ahmed

7,3535 gold badges30 silver badges50 bronze badges

answered Apr 30, 2018 at 10:01

Vinayak Singh's user avatar

I found the followig tip helpful, to eliminate this issue in Tomcat —

be sure to load the driver first doing a Class.forName(»
org.postgresql.Driver»); in your code.

This is from the post — https://www.postgresql.org/message-id/e13c14ec050510103846db6b0e@mail.gmail.com

The jdbc code worked fine as a standalone program but, in TOMCAT it gave the error -‘No suitable driver found’

answered Jan 19, 2018 at 15:52

A Venkatraman's user avatar

2

No matter how old this thread becomes, people would continue to face this issue.

My Case: I have the latest (at the time of posting) OpenJDK and maven setup. I had tried all methods given above, with/out maven and even solutions on sister posts on StackOverflow. I am not using any IDE or anything else, running from bare CLI to demonstrate only the core logic.

Here’s what finally worked.

  • Download the driver from the official site. (for me it was MySQL https://www.mysql.com/products/connector/). Use your flavour here.
  • Unzip the given jar file in the same directory as your java project. You would get a directory structure like this. If you look carefully, this exactly relates to what we try to do using Class.forName(....). The file that we want is the com/mysql/jdbc/Driver.class

https://i.imgur.com/VgpwatQ.png

  • Compile the java program containing the code.
javac App.java
  • Now load the director as a module by running
java --module-path com/mysql/jdbc -cp ./ App

This would load the (extracted) package manually, and your java program would find the required Driver class.


  • Note that this was done for the mysql driver, other drivers might require minor changes.
  • If your vendor provides a .deb image, you can get the jar from /usr/share/java/your-vendor-file-here.jar

answered Oct 17, 2020 at 8:59

Yash Kumar Verma's user avatar

Yash Kumar VermaYash Kumar Verma

9,2182 gold badges16 silver badges28 bronze badges

Summary:

  • Soln2 (recommend)::

    • 1 . put mysql-connector-java-8.0.28.jar file in the <where you install your Tomcat>/lib.
  • Soln1::

    • 1 . put mysql-connector-java-8.0.28.jar file in the WEB-INF/lib.
    • 2 . use Class.forName("com.mysql.cj.jdbc.Driver"); in your Servlet Java code.

Soln1 (Ori Ans) //-20220304

In short:

  1. make sure you have the mysql-connector-java-8.0.28.jar file in the WEB-INF/lib
  2. make sure you use the Class.forName("com.mysql.cj.jdbc.Driver");

jar & class for jdbc connect


additional notes (not important), base on my trying (could be wrong)::

  • 1.1 putting the jar directly inside the Java build path doesnt work

  • 1.2. putting the jar in Data management > Driver Def > MySQL JDBC Driver > then add it as library to Java Build path doesnt work.

  • 1.3 => it has to be inside the WEB-INF/lib (I dont know why)

  • 1.4 using version mysql-connector-java-8.0.28.jar works, only version 5.1 available in Eclipse MySQL JDBC Driver setting doesnt matter, ignore it.

    <see How to connect to MySql 8.0 database using Eclipse Database Management Perspective >

  •     Class.forName("com.mysql.cj.jdbc.Driver");
        Class.forName("com.mysql.jdbc.Driver");
    

    both works,
    but the Class.forName("com.mysql.jdbc.Driver"); is deprecated.

    Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
    

    <see https://www.yawintutor.com/no-suitable-driver-found-for-jdbcmysql-localhost3306-testdb/ >

  • If you want to connect to a MySQL database, you can use the type-4 driver named Connector/} that’s available for free from the MySQL website. However, this driver is typically included in Tomcat’s lib directory. As a result, you don’t usually need to download this driver from the MySQL site.

    — Murach’s Java Servlets and JSP

    I cant find the driver in Tomcat that the author is talking about, I need to use the mysql-connector-java-8.0.28.jar.
    <(striked-out) see updated answer soln2 below>

  • If you’re working with an older version of Java, though, you need to use the forName method of the Class class to explicitly load the driver before you call the getConnection method

    Even with JDBC 4.0, you sometimes get a message that says, «No suitable driver found.» In that case, you can use the forName method of the Class class to explicitly load the driver. However, if automatic driver loading works, it usually makes sense to remove this method call from your code.

    How to load a MySQL database driver prior to JDBC 4.0

    Class.forName{"com.mysql.jdbc.Driver");

    — Murach’s Java Servlets and JSP

    I have to use Class.forName("com.mysql.cj.jdbc.Driver"); in my system, no automatic class loading. Not sure why.
    <(striked-out) see updated answer soln2 below>

  • When I am using a normal Java Project instead of a Dynamic Web Project in Eclipse,

    I only need to add the mysql-connector-java-8.0.28.jar to Java Build Path directly,

    then I can connect to the JDBC with no problem.

    However, if I am using Dynamic Web Project (which is in this case), those 2 strict rules applies (jar position & class loading).

    <see TOMCAT ON ECLIPSE java.sql.SQLException: No suitable driver found for jdbc:mysql >


Soln2 (Updated Ans) //-20220305_12

In short:

  • 1 . put mysql-connector-java-8.0.28.jar file in the <where you install your Tomcat>/lib.

    eg: G:plaJavaapache-tomcat-10.0.16libmysql-connector-java-8.0.28.jar

    (and for an Eclipse Dynamic Web Project, the jar will then be automatically put inside in your project’s Java build path > Server Runtime [Apache Tomcat v10.0].)

put jar in Tomcat/lib


Additional notes::

for soln1::

  1. put mysql-connector-java-8.0.28.jar file in the WEB-INF/lib.
  2. use Class.forName("com.mysql.cj.jdbc.Driver"); in your Servlet Java code.

this will create an WARNING:

WARNING: The web application [LearnJDBC] appears to have started a thread named [mysql-cj-abandoned-connection-cleanup] but has failed to stop it. This is very likely to create a memory leak. Stack trace of thread:

<see The web application [] appears to have started a thread named [Abandoned connection cleanup thread] com.mysql.jdbc.AbandonedConnectionCleanupThread >

and that answer led me to soln2.

for soln2::

    1. put mysql-connector-java-8.0.28.jar file in the <where you install your Tomcat>/lib.

    this will create an INFO:

    INFO: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
    
  • you can just ignore it.

    <see How to fix «JARs that were scanned but no TLDs were found in them » in Tomcat 9.0.0M10 >

  • (you should now understand what Murach’s Java Servlets and JSP was talking about: the jar in Tomcat/lib & the no need for Class.forName("com.mysql.cj.jdbc.Driver");)

  • to kinda fix it //-20220307_23

    Tomcat 8.5. Inside catalina.properties, located in the /conf directory set:
    tomcat.util.scan.StandardJarScanFilter.jarsToSkip=*.jar

    How to fix JSP compiler warning: one JAR was scanned for TLDs yet contained no TLDs?

    skip scan in Tomcat/lib jar

answered Mar 5, 2022 at 4:30

Nor.Z's user avatar

Nor.ZNor.Z

3754 silver badges11 bronze badges

It might be worth noting that this can also occur when Windows blocks downloads that it considers to be unsafe. This can be addressed by right-clicking the jar file (such as ojdbc7.jar), and checking the ‘Unblock’ box at the bottom.

Windows JAR File Properties Dialog:
Windows JAR File Properties Dialog

brasofilo's user avatar

brasofilo

25.2k15 gold badges90 silver badges178 bronze badges

answered May 10, 2017 at 20:55

user7994072's user avatar

As well as adding the MySQL JDBC connector ensure the context.xml (if not unpacked in the Tomcat webapps folder) with your DB connection definitions are included within Tomcats conf directory.

answered Jun 29, 2017 at 16:07

feistyfawn's user avatar

feistyfawnfeistyfawn

1011 silver badge4 bronze badges

A very silly mistake which could be possible resulting is adding of space at the start of the JDBC URL connection.

What I mean is:-

suppose u have bymistake given the jdbc url like

String jdbcUrl=" jdbc:mysql://localhost:3306/web_customer_tracker?useSSL=false&serverTimeZone=UTC";

(Notice there is a space in the staring of the url, this will make the error)

the correct way should be:

String jdbcUrl="jdbc:mysql://localhost:3306/web_customer_tracker?useSSL=false&serverTimeZone=UTC";

(Notice no space in the staring, you may give space at the end of the url but it is safe not to)

iElden's user avatar

iElden

1,2441 gold badge14 silver badges24 bronze badges

answered Apr 20, 2019 at 7:44

ankkol2011's user avatar

Run java with CLASSPATH environmental variable pointing to driver’s JAR file, e.g.

CLASSPATH='.:drivers/mssql-jdbc-6.2.1.jre8.jar' java ConnectURL

Where drivers/mssql-jdbc-6.2.1.jre8.jar is the path to driver file (e.g. JDBC for for SQL Server).

The ConnectURL is the sample app from that driver (samples/connections/ConnectURL.java), compiled via javac ConnectURL.java.

answered Jul 30, 2019 at 16:06

kenorb's user avatar

kenorbkenorb

149k79 gold badges667 silver badges722 bronze badges

I was using jruby, in my case I created under config/initializers

postgres_driver.rb

$CLASSPATH << '~/.rbenv/versions/jruby-1.7.17/lib/ruby/gems/shared/gems/jdbc-postgres-9.4.1200/lib/postgresql-9.4-1200.jdbc4.jar'

or wherever your driver is, and that’s it !

Moinuddin Quadri's user avatar

answered Feb 14, 2017 at 19:47

Ale Guro's user avatar

I had this exact issue when developing a Spring Boot application in STS, but ultimately deploying the packaged war to WebSphere(v.9). Based on previous answers my situation was unique. ojdbc8.jar was in my WEB-INF/lib folder with Parent Last class loading set, but always it says it failed to find the suitable driver.

My ultimate issue was that I was using the incorrect DataSource class because I was just following along with online tutorials/examples. Found the hint thanks to David Dai comment on his own question here: Spring JDBC Could not load JDBC driver class [oracle.jdbc.driver.OracleDriver]

Also later found spring guru example with Oracle specific driver: https://springframework.guru/configuring-spring-boot-for-oracle/

Example that throws error using org.springframework.jdbc.datasource.DriverManagerDataSource based on generic examples.

@Config
@EnableTransactionManagement
public class appDataConfig {
 * Other Bean Defs *
    @Bean
    public DataSource dataSource() {
        // configure and return the necessary JDBC DataSource
        DriverManagerDataSource dataSource = new DriverManagerDataSource("jdbc:oracle:thin:@//HOST:PORT/SID", "user", "password");
        dataSource.setSchema("MY_SCHEMA");
        return dataSource;
    }
}

And the corrected exapmle using a oracle.jdbc.pool.OracleDataSource:

@Config
@EnableTransactionManagement
public class appDataConfig {
/* Other Bean Defs */
@Bean
    public DataSource dataSource() {
        // configure and return the necessary JDBC DataSource
        OracleDataSource datasource = null;
        try {
            datasource = new OracleDataSource();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        datasource.setURL("jdbc:oracle:thin:@//HOST:PORT/SID");
        datasource.setUser("user");
        datasource.setPassword("password");

        return datasource;
    }
}

answered Jul 19, 2017 at 20:31

Ryan D's user avatar

Ryan DRyan D

93310 silver badges14 bronze badges

I was having the same issue with mysql datasource using spring data that would work outside but gave me this error when deployed on tomcat.

The error went away when I added the driver jar mysql-connector-java-8.0.16.jar to the jres lib/ext folder

However I did not want to do this in production for fear of interfering with other applications. Explicity defining the driver class solved this issue for me

    spring.datasource.driver-class-name: com.mysql.cj.jdbc.Driver

answered May 14, 2019 at 19:22

Jag's user avatar

You will get this same error if there is not a Resource definition provided somewhere for your app — most likely either in the central context.xml, or individual context file in conf/Catalina/localhost. And if using individual context files, beware that Tomcat freely deletes them anytime you remove/undeploy the corresponding .war file.

answered Sep 18, 2020 at 21:40

em_bo's user avatar

em_boem_bo

5945 silver badges13 bronze badges

For me the same error occurred while connecting to postgres while creating a dataframe from table .It was caused due to,the missing dependency. jdbc dependency was not set .I was using maven for the build ,so added the required dependency to the pom file from maven dependency

jdbc dependency

answered Feb 27, 2021 at 5:04

manojvinibabu's user avatar

For me adding below dependency to pom.xml file just solved like magic! I had no mysql connector dependency and even adding mssql jdbc jar file to build path did not work either.

    <dependency> 
        <groupId>com.microsoft.sqlserver</groupId>
        <artifactId>mssql-jdbc</artifactId>
        <version>9.4.0.jre11</version>
    </dependency>

OneCricketeer's user avatar

OneCricketeer

168k18 gold badges124 silver badges229 bronze badges

answered Sep 23, 2021 at 18:38

GSN's user avatar

GSNGSN

1132 silver badges12 bronze badges

1

In my case I was working on a Java project with Maven and encountered this error.
In your pom.xml file make sure you have this dependencies

<dependencies>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.11</version>
    </dependency>
  </dependencies>

and where you create connection have something like this

public Connection createConnection() {
        try {
            String url = "jdbc:mysql://localhost:3306/yourDatabaseName";
            String username = "root"; //your my sql username here
            String password = "1234"; //your mysql password here

            Class.forName("com.mysql.cj.jdbc.Driver");
            return DriverManager.getConnection(url, username, password);
        } catch (SQLException | ClassNotFoundException e) {
            e.printStackTrace();
        }

        return null;
    }

OneCricketeer's user avatar

OneCricketeer

168k18 gold badges124 silver badges229 bronze badges

answered May 26, 2020 at 19:42

Gabriel Arghire's user avatar

Gabriel ArghireGabriel Arghire

1,6431 gold badge16 silver badges33 bronze badges

2

I ran into the same error. In my case, the JDBC URL was correct, but the issue was with classpath. However, adding MySQL connector’s JAR file to the -classpath or -cp (or in the case of an IDE, as a library) also doesn’t resolve the issue. I will have to move the JAR file to the location of Java bycode and run java -cp :mysql_connector.jar to make this work. I’m leaving this here in case someone ran into the same issue as that of mine.

answered Mar 26, 2022 at 4:48

sammy's user avatar

sammysammy

1013 silver badges2 bronze badges

faced same issue. in my case ‘:’ colon before ‘//’ (jdbc:mysql://localhost:3306/dbname) was missing, and it just fixed the problem.
make sure : and // are placed properly.

answered May 25, 2022 at 18:46

Dipak_Patil's user avatar

I encountered this issue by putting a XML file into the src/main/resources wrongly, I deleted it and then all back to normal.

answered Mar 26, 2019 at 2:57

jerryleooo's user avatar

jerryleooojerryleooo

81310 silver badges16 bronze badges

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • No suitable context info for active keying set blender ошибка
  • No such ship design stellaris ошибка