Ошибка no suitable driver found for jdbc mysql

I am trying to create a connection to my database, when I put test my code using the main method, it works seamlessly. However, when trying to access it through Tomcat 7, it fails with error:

No suitable driver found for jdbc:mysql://localhost/dbname. 

I am using pooling. I put in mysql connector (5.1.15), dbcp (1.4) , and pool(1.4.5) libraries in WEB-INF/lib and in .classpath as well. I am using Eclipse IDE. My code for the database driver is:

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

import org.apache.tomcat.dbcp.dbcp.ConnectionFactory;
import org.apache.tomcat.dbcp.dbcp.DriverManagerConnectionFactory;
import org.apache.tomcat.dbcp.dbcp.PoolableConnectionFactory;
import org.apache.tomcat.dbcp.dbcp.PoolingDriver;
import org.apache.tomcat.dbcp.pool.impl.GenericObjectPool;

public class DatabaseConnector {
    public static String DB_URI = "jdbc:mysql://localhost/dbname";
    public static String DB_USER = "test";
    public static String DB_PASS = "password";

    // Singleton instance
    protected static DatabaseConnector _instance;

    protected String _uri;
    protected String _username;
    protected String _password;

    /**
     * Singleton, so no public constructor
     */
    protected DatabaseConnector(String uri, String username, String password) {
        _uri = uri;
        _username = username;
        _password = password;

        GenericObjectPool connectionPool = new GenericObjectPool(null);
        ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(
            _uri, _username, _password);
        PoolableConnectionFactory poolableConnectionFactory =
            new PoolableConnectionFactory(connectionFactory, connectionPool,
                                            null, null, false, true);
        PoolingDriver driver = new PoolingDriver();
        driver.registerPool("test", connectionPool);
    }

    /**
     * Returns the singleton instance
     */
    public static DatabaseConnector getInstance() {
        if (_instance == null) {
            _instance = new DatabaseConnector(DB_URI, DB_USER, DB_PASS);
        }
        return _instance;
    }

    /**
     * Returns a connection to the database
     */
    public Connection getConnection() {
        Connection con = null;
        try {
            con = DriverManager.getConnection("jdbc:apache:commons:dbcp:test");
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return con;
    }
}

Start of my stack trace:

Apr 5, 2011 9:49:14 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [Login] in context with path [/Project] 
threw exception
java.lang.RuntimeException: java.sql.SQLException: 
No suitable driver found for jdbc:mysql://localhost/dbname

What is causing this error?

asked Apr 5, 2011 at 18:30

Tamer's user avatar

TamerTamer

1,7144 gold badges16 silver badges15 bronze badges

2

Try putting the driver jar in the server lib folder. ($CATALINA_HOME/lib)

I believe that the connection pool needs to be set up even before the application is instantiated. (At least that’s how it works in Jboss)

answered Apr 5, 2011 at 18:57

uncaught_exceptions's user avatar

3

The reason you got this error:

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

Is because you forgot to register your mysql jdbc driver with the java application.

This is what you wrote:

Connection con = null;
try {
    con = DriverManager.getConnection("jdbc:apache:commons:dbcp:test");
} catch (SQLException e) {
    throw new RuntimeException(e);
}

Should be this:

Connection con = null;
try {
    //registering the jdbc driver here, your string to use 
    //here depends on what driver you are using.
    Class.forName("something.jdbc.driver.YourFubarDriver");   
    con = DriverManager.getConnection("jdbc:apache:commons:dbcp:test");
} catch (SQLException e) {
    throw new RuntimeException(e);
}

You’ll have to read the manual on your specific mysql jdbc driver to find the exact string to place inside the the Class.forName(«…») parameter.

Class.forName not required with JDBC v.4

Starting with Java 6, Class.forName("something.jdbc.driver.YourFubarDriver") is not necessary anymore if you use a recent (JDBC v.4) driver. For details read this: http://onjava.com/pub/a/onjava/2006/08/02/jjdbc-4-enhancements-in-java-se-6.html

answered Sep 14, 2011 at 17:43

Eric Leschinski's user avatar

Eric LeschinskiEric Leschinski

145k95 gold badges412 silver badges332 bronze badges

8

I had the same problem using Tomcat7 with mysql-connector-java-5.1.26 that I put in both my $CATALINA_HOME/lib and WEB-INF/lib, just in case. But it wouldn’t find it until I used either one of these two statements before getting the connection:

DriverManager.registerDriver(new com.mysql.jdbc.Driver ());

OR

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

I then followed up with removing mysql-connector-java-5.1.26 from $CATALINA_HOME/lib and the connection still works.

answered Oct 8, 2013 at 22:26

ybenjira's user avatar

ybenjiraybenjira

5394 silver badges4 bronze badges

7

When running tomcat out of eclipse it won’t pick the lib set in CATALINA_HOME/lib, there are two ways to fix it. Double click on Tomcat server in eclipse servers view, it will open the tomcat plugin config, then either:

  1. Click on «Open Launch Config» > Classpath tab set the mysql connector/j jar location.
    or
  2. Server Location > select option which says «Use Tomcat installation (take control of Tomcat installation)»

DaSourcerer's user avatar

DaSourcerer

6,1785 gold badges31 silver badges54 bronze badges

answered Jan 4, 2014 at 20:02

bjethwan's user avatar

bjethwanbjethwan

891 silver badge3 bronze badges

0

I had the mysql jdbc library in both $CATALINA_HOME/lib and WEB-INF/lib, still i got this error . I needed Class.forName(«com.mysql.jdbc.Driver»); to make it work.

answered Nov 5, 2014 at 15:58

nondescript's user avatar

nondescriptnondescript

1,4761 gold badge13 silver badges16 bronze badges

add the artifact from maven.

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

answered Oct 1, 2016 at 12:17

Tunde Pizzle's user avatar

Tunde PizzleTunde Pizzle

7871 gold badge9 silver badges18 bronze badges

1

I’m running Tomcat 7 in Eclipse with Java 7 and using the jdbc driver for MSSQL sqljdbc4.jar.

When running the code outside of tomcat, from a standalone java app, this worked just fine:

        connection = DriverManager.getConnection(conString, user, pw);

However, when I tried to run the same code inside of Tomcat 7, I found that I could only get it work by first registering the driver, changing the above to this:

        DriverManager.registerDriver(new com.microsoft.sqlserver.jdbc.SQLServerDriver());
        connection = DriverManager.getConnection(conString, user, pw);

answered Oct 21, 2014 at 20:51

nick's user avatar

Use:

try {

    Class.forName("com.mysql.jdbc.Driver").newInstance();
    System.out.println("Registro exitoso");

} catch (Exception e) {

    System.out.println(e.toString());

}

DriverManager.getConnection(..

Max's user avatar

Max

1,3259 silver badges20 bronze badges

answered Dec 26, 2016 at 23:39

Joan Payano Camacho's user avatar

2

Bro, you can also write code as below:

import java.sql.*;
import java.io.*;
public class InsertDatabase {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    try
    {  
        Class.forName("com.mysql.jdbc.Driver");  
        Connection con=DriverManager.getConnection(  
        "jdbc:mysql://localhost:3306/Maulik","root","root");  

        Statement stmt=con.createStatement();  
        ResultSet rs=stmt.executeQuery("select * from Employee");  
        while(rs.next())  
        System.out.println(rs.getInt(1)+"  "+rs.getString(2)+"  "+rs.getString(3));  
        con.close();
    }

    catch(Exception e)
    {
        System.out.println(e);
    }

        }  

}

answered Jan 30, 2017 at 11:03

Maulik's user avatar

MaulikMaulik

3494 silver badges19 bronze badges

I also had the same problem some time before, but I solved that issue.

There may be different reasons for this exception.
And one of them may be that the jar you are adding to your lib folder may be old.

Try to find out the latest mysql-connector-jar version and add that to your classpath.
It may solve your issue. Mine was solved like that.

j0k's user avatar

j0k

22.5k28 gold badges79 silver badges89 bronze badges

answered Jan 10, 2013 at 7:11

Ankit Pawar's user avatar

I had the same problem, all you need to do is define classpath environment variable for tomcat, you can do it by adding a file, in my case C:apache-tomcat-7.0.30binsetenv.bat, containing:

set "CLASSPATH=%CLASSPATH%;%CATALINA_HOME%libmysql-connector-java-5.1.14-bin.jar"

then code, in my case:

Class.forName("com.mysql.jdbc.Driver").newInstance(); 
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/database_name", "root", "");

works fine.

Aliaksandr Belik's user avatar

answered Sep 19, 2012 at 14:04

test30's user avatar

test30test30

3,40633 silver badges26 bronze badges

2

if you are using netbeans you must add Mysql JDBC driver in the library list of the project, in the properties of your project

Gapchoos's user avatar

Gapchoos

1,4224 gold badges20 silver badges40 bronze badges

answered Jul 5, 2012 at 19:10

Sérgio Silva's user avatar

Most of time it happen because two mysql-connector-java-3.0.14-production-bin.jar file.
One in lib folder of tomcat and another in classpath of the project.

Just try to remove mysql-connector-java-3.0.14-production-bin.jar from lib folder.

This way it is working for me.

answered Jun 3, 2014 at 12:35

RKP's user avatar

From what i have observed there might be two reasons for this Exception to occur:
(1)Your Driver name is not spelled Correctly.
(2)Driver hasn’t been Associated Properly with the Java Project
Steps to follow in Eclipse:
(1)Create a new Java Project.
(2)copy The connector Jar file
(3)Right Click on the Java project and paste it there.
(4)Right click on the Java project -> Properties ->Java Build Path — >libraries-> Add Jar ->choose ur project(select the jar file from dropdown) and click ok.

answered Feb 10, 2015 at 1:14

Abhishek J's user avatar

The solution is straightforward.

Make sure that the database connector can be reached by your classpath when running (not compiling) the program, e.g.:

java -classpath .;c:pathtomysql-connector-java-5.1.39.jar YourMainClass 

Also, if you’re using an old version of Java (pre JDBC 4.0), before you do DriverManager.getConnection this line is required:

Class.forName("your.jdbc.driver.TheDriver"); // this line is not needed for modern Java

answered Jul 29, 2016 at 10:23

Pacerier's user avatar

PacerierPacerier

85.6k106 gold badges366 silver badges631 bronze badges

When developing using Ubuntu (Xubuntu 12.04.1) I ‘HAD’ to do the following:

Using

Eclipse Juno (downloaded, not installed via the software centre),
Tomcat 7 (downloaded in a custom user directory) also added as a Server in Eclipse,
Dynamic Web Project with a 3.0 Servlet,
MySQL Server on localhost configured and tested with user and password (make sure to test)
MySQL connector driver 5.1.24 jar,

I ‘HAD’, and I repeat ‘HAD’, to us the Class.Load(«com.mysql.jdbc.Driver») statement along with adding the connector driver.jar to be in the web project lib folder for it to work in this situation.

IMPORTANT!!: after you copy the driver.jar to the lib make sure you refresh your project in Eclipse before running the servlet via Tomcat.

I did try adding the connector driver jar file via the Build Path with and without ClassLoad but it did not work!

Hope this helps anyone starting development with this specific situation: the Java community provides a ‘LOT’ of documentation but there are so many variables its hard to cover all of them and it makes things very hard on the new guy.

I think if someone could explain why Class.Load is required here (in this situation) it would be beneficial.

Enjoy

answered Mar 14, 2013 at 19:06

MtlMike's user avatar

Since no one gave this answer, I would also like to add that, you can just add the jdbc driver file(mysql-connector-java-5.1.27-bin.jar in my case) to the lib folder of your server(Tomcat in my case). Restart the server and it should work.

answered Dec 3, 2013 at 17:51

Susie's user avatar

SusieSusie

5,01810 gold badges53 silver badges74 bronze badges

1

  1. Put mysql-connector-java-5.0.8-bin.jar in $CATALINA_HOME/lib

  2. Check for typo in connection url, example
    «jdbc:mysql://localhost:3306/report» (‘report’ here is the db name)

  3. Make sure to use machine name(example : localhost instead of ip address(127.0.0.1))

answered Aug 15, 2015 at 12:08

Bruce's user avatar

BruceBruce

7838 silver badges17 bronze badges

Add the driver class to the bootstrapclasspath. The problem is in java.sql.DriverManager that doesn’t see the drivers loaded by ClassLoaders other than bootstrap ClassLoader.

answered Oct 27, 2015 at 22:05

arathim's user avatar

0

From other stackoverflow thread:

«Second. Make sure that you have MySQL JDBC Driver aka Connector/J in JMeter’s classpath. If you don’t — download it, unpack and drop mysql-connector-java-x.xx.xx-bin.jar to JMeter’s /lib folder. JMeter restart will be required to pick the library up»

Please be sure that .jar file is added directly to the lib folder.

answered Apr 25, 2016 at 17:47

adrian filipescu's user avatar

You can stick the jar in the path of run time of jboss like this:

C:Useruserworkspacejboss-as-web-7.0.0.FinalstandalonedeploymentsMYapplicationEAR.eartest.warWEB-INFlib
ca marche 100%

ChrisF's user avatar

ChrisF

134k31 gold badges254 silver badges325 bronze badges

answered Jun 7, 2015 at 16:30

user4983785's user avatar

0

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]

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.

Друзья, помогите разобраться уже пару дней пытаюсь решить проблему, изучаю работу с БД, создал проект в Idea и БД на MySQL, вроде все подключик как положено, mysql connector импортировал в проект, но при запуске проекта выдает ошибку No suitable driver found for jdbc:mysql:localhost:3306/Park, в чем проблема не пойму mysql connector ставил разных версий и просто так и через maven результат один, в чем может быть проблема.
Если протестить соединение с БД из вкладки Database то проверка проходит, а когда запускаешь проект выдает ошибку

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'
}

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.

Понравилась статья? Поделить с друзьями:
  • Ошибка no such process transmission
  • Ошибка no such partition что делать
  • Ошибка no such interface supported
  • Ошибка no such host is known
  • Ошибка no such file or directory питон