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

146k95 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.7k106 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,03810 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]

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.

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.

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

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 power carrier ошибка
  • No such file or directory ошибка python
  • No port for remote debugger esxi ошибка
  • No such file or directory git bash ошибка
  • No more room in hell ошибка