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

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,7244 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

147k96 gold badges418 silver badges335 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

5494 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,2985 gold badges32 silver badges55 bronze badges

answered Jan 4, 2014 at 20:02

bjethwan's user avatar

bjethwanbjethwan

971 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

7971 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.6k28 gold badges79 silver badges90 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.30\bin\setenv.bat, containing:

set "CLASSPATH=%CLASSPATH%;%CATALINA_HOME%\lib\mysql-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,51634 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,4225 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:\path\to\mysql-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

86.4k107 gold badges368 silver badges635 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,04810 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

7938 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:\User\user\workspace\jboss-as-web-7.0.0.Final\standalone\deployments\MYapplicationEAR.ear\test.war\WEB-INF\lib
ca marche 100%

ChrisF's user avatar

ChrisF

135k31 gold badges255 silver badges325 bronze badges

answered Jun 7, 2015 at 16:30

user4983785's user avatar

0

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,7244 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

147k96 gold badges418 silver badges335 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

5494 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,2985 gold badges32 silver badges55 bronze badges

answered Jan 4, 2014 at 20:02

bjethwan's user avatar

bjethwanbjethwan

971 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

7971 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.6k28 gold badges79 silver badges90 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.30\bin\setenv.bat, containing:

set "CLASSPATH=%CLASSPATH%;%CATALINA_HOME%\lib\mysql-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,51634 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,4225 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:\path\to\mysql-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

86.4k107 gold badges368 silver badges635 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,04810 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

7938 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:\User\user\workspace\jboss-as-web-7.0.0.Final\standalone\deployments\MYapplicationEAR.ear\test.war\WEB-INF\lib
ca marche 100%

ChrisF's user avatar

ChrisF

135k31 gold badges255 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]

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.

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.

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 such user ошибка
  • Nmi ошибка ожидания nc210
  • Non page area windows 10 ошибка
  • No efi system partition was found ошибка
  • No such file or directory python ошибка